简体   繁体   中英

form validation exception not catching by Exception in laravel 5.1?

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 422 exception. but it is not catching from app/Exceptions/Handler@render but working fine with abort(422) .

How can I solve this?

You can catch simply by doing

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM