首页 > 解决方案 > 捕获 ValidationException 时返回自定义 json 响应

问题描述

我有一个控制器入口点,我在其中从我的 ProductService 执行另一个方法 inisde 一个 try catch 块,我假装捕获 $this->productServvice->create() 方法中可能发生的所有异常,除了验证错误,如果它是验证错误 $e->getMessage() 不会做,因为我会得到通用响应“给定数据无效”而不是完整的自定义消息。在阅读了一些之后,我决定在 laravel Handler 类中使用 render 方法,我添加了这个:

//In order to react to validation exceptions I added some logic to render method, but it won't actually work, I'm still getting normal exception message returned.

public function render($request, Exception $exception)
    {
        if ($request->ajax() && $exception instanceof ValidationException) {
            return response()->json([
                'message' => $e->errors(),
            ],422);
        }

        return parent::render($request, $exception);
}

但是我仍然收到默认消息,这意味着我的 catch 块正在捕获正常异常而不是我的自定义渲染方法......

在我的控制器中,try catch 块如下所示:

try
        {
            $this->productService->create($request);

            return response()->json([
                'product' => $product,
            ], 200);

        } 
        //I want to catch all exceptions except Validation fails here, and return simple error message to view as 
        json 
        catch (\Exception $e)
        {
            return response()->json([
                'message' => $e->getMessage(),
            ], $e->getStatus() );
        }

此外,在 ValidationException 中,我不能使用 $e->getCode、$e->getStatus(),它总是返回 0 或 smetimes 1,afaik 它应该是 422,这就是为什么在我的渲染方法中我手动返回 422。在我的带有正常异常 $e->getCode() 的 try catch 块中正常工作,这是为什么呢?

标签: phplaravel

解决方案


在您的渲染函数中,您引用了一个未定义的错误实例,您定义了 Exception $exception 但您引用的是 $e->errors();

你的代码应该是:

public function render($request, Exception $exception)
    {
        if ($request->ajax() && $exception instanceof ValidationException) {
            return response()->json([
                'message' => $exception->errors(),
            ],422);
        }

        return parent::render($request, $exception); 
}

更改 $e->errors(); 到 $exception->errors();


推荐阅读