form validation exception not catching by Exception in laravel 5.1?

戏子无情 提交于 2020-01-07 06:49:08

问题


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

     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@render but working fine with abort(422).

How can I solve this?


回答1:


When Form Request fails to validate your data it fires the failedValidation(Validator $validator) method that throws HttpResponseException with 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.

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

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




回答2:


You can catch simply by doing

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


来源:https://stackoverflow.com/questions/31217541/form-validation-exception-not-catching-by-exception-in-laravel-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!