Laravel – customize 404, validation & other exceptions in one place – return a response of your choice

Laravel exception handler

If you want to customise responses for exceptions in Laravel, such as 404, validation exceptions, etc. in one place, this lesson will show you how to do that.

When you might need this

Assuming you’re building some rest APIs with Laravel and want to return a JSON structure of your own instead of what Laravel returns by default, you need to catch all exception and return the JSON response of your choice.

Using a 404 exception as an example…

Let’s look at how you can customise the 404 exception responses in Laravel 8 and 7.

The reason we’re going to do this in Laravel 7 and 8 is that the exception handling done differently for the two versions on Laravel.

Handling all 404 exceptions in Laravel 8

To handle 404 and most other options, you can do this in the register method of Handler.php, located in App\Exceptions;

Here we will catch all 404 and return a JSON response if the request expects a JSON:

// App\Exceptions\Handler.php
/**
 * Register the exception handling callbacks for the application.
 *
 * @return void
*/
public function register() {

    // handle all 404
    $this->renderable(function (NotFoundHttpException $e, $request) {
        if($request->expectsJson()) {
            
            // return json response of your chosen
            return response()->json([
                'status' => false,
                'code' => 404,
                'message' => 'Resource not found',
                'data' => null,
            ]);
        }
    });
}

Customize 404 exception responses in Laravel 7

Similarly, in Laravel 7, we catch the 404 exception in the Handler class but this time we do it in the render method of the class, instead of the regiser method as we did for Laravel 8:

//
/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Throwable  $exception
 * @return \Symfony\Component\HttpFoundation\Response
 *
 * @throws \Throwable
 */
public function render($request, Throwable $exception)
{
    // handle all 404
    if ($exception instanceof NotFoundHttpException && $request->expectsJson()) {
        
        // return json response of your chosen
        return response()->json([
            'status' => false,
            'code' => 404,
            'message' => 'Resource not found',
            'data' => null,
        ]);
    }

    return parent::render($request, $exception);
}

As you can see, the only difference really is how we determine which exception was thrown.

Pro tip: The example above applies to many other exception types in. Examples include ValidationException and AuthorizationException. So, feel free to handle other exceptions as you see fit.

Happy coding!

 

Leave a Reply

Your email address will not be published. Required fields are marked *