laravel 表单验证异常没有被laravel 5.1中的异常捕获?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31217541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:52:29  来源:igfitidea点击:

form validation exception not catching by Exception in laravel 5.1?

phplaravelexceptionlaravel-5laravel-5.1

提问by gsk

In laravel5, I have catching all error at app/Exceptions/Handler@renderfunction and it was working fine. code given below,

在 laravel5 中,我捕获了app/Exceptions/Handler@render函数中的所有错误,并且运行良好。下面给出的代码,

     public function render($request, Exception $e) {
        $error_response['error'] = array(
            'code' => NULL,
            'message' => NULL,
            'debug' => NULL
        );
        if ($e instanceof HttpException && $e->getStatusCode() == 422) {
            $error_response['error']['code'] = 422;
            $error_response['error']['message'] = $e->getMessage();
            $error_response['error']['debug'] = null;
            return new JsonResponse($error_response, 422);
        } 
 }
        return parent::render($request, $e);
}

But in laravel5.1,When form validation failes,it throws error message with 422exception. but it is not catching from app/Exceptions/Handler@renderbut working fine with abort(422).

但是在laravel5.1中,当表单验证失败时,它会抛出异常的错误信息422。但它不是从追赶 app/Exceptions/Handler@render但做工精细abort(422)

How can I solve this?

我该如何解决这个问题?

回答by Shahid

You can catch simply by doing

你可以简单地通过做

public function render($request, Exception $e) {
    if($e instanceof ValidationException) {
        // Your code here
    }
}

回答by Maxim Lanin

When Form Request fails to validate your data it fires the failedValidation(Validator $validator)method that throws HttpResponseExceptionwith a fresh Redirect Response, but not HttpException. This exception is caught via Laravel Router in its run(Request $request)method and that fetches the response and fires it. So you don't have any chance to handle it via your Exceptions Handler.

当表单请求无法验证您的数据时,它会触发failedValidation(Validator $validator)抛出HttpResponseException新重定向响应的方法,但不会触发HttpException. 这个异常是通过 Laravel Router 的run(Request $request)方法捕获的,它获取响应并触发它。所以你没有任何机会通过你的异常处理程序来处理它。

But if you want to change this behaviour you can overwrite failedValidationmethod in your Abstract Request or any other Request class and throw your own exception that you will handle in the Handler.

但是,如果您想更改此行为,您可以覆盖failedValidation抽象请求或任何其他请求类中的方法,并抛出您将在处理程序中处理的您自己的异常。

Or you can just overwrite response(array $errors)and create you own response that will be proceed by the Router automatically.

或者您可以覆盖response(array $errors)并创建您自己的响应,这些响应将由路由器自动处理。