3

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?

2 Answers 2

5

You can catch simply by doing

public function render($request, Exception $e) {
    if($e instanceof ValidationException) {
        // Your code here
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me in Laravel 5.4 - just remember to add your use statement to the top of the Handler class: use Illuminate\Validation\ValidationException; (I initially forgot it!)
3

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 Comments

how can I or where should I overwrite failedValidation method?
@MuhammedShihabuddeen if you want to have this behaviour for every FormRequest, you have to do it in your abstract Request class (/app/Http/Requests/Request). If you want to have it for the certain Request, you have to overwrite it right in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.