【问题标题】:Return custom json response when catching ValidationException捕获 ValidationException 时返回自定义 json 响应
【发布时间】:2020-09-30 16:20:37
【问题描述】:

我有一个控制器入口点,在那里我从我的 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 块中正常工作,为什么会这样?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    在您的渲染函数中,您引用了一个未定义的错误实例,您定义了 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();

    【讨论】:

    • 你是对的,但我仍然无法让我的验证处理程序方法无法触发......
    猜你喜欢
    • 2017-04-27
    • 2017-03-11
    • 2019-10-24
    • 1970-01-01
    • 2019-08-03
    • 2020-04-23
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    相关资源
    最近更新 更多