gsk
gsk

Reputation: 2379

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

How can I solve this?

Upvotes: 3

Views: 10754

Answers (2)

Shahid
Shahid

Reputation: 357

You can catch simply by doing

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

Upvotes: 5

Maxim Lanin
Maxim Lanin

Reputation: 4531

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.

Upvotes: 3

Related Questions