How to show Exception responses as JSON in Laravel

While working on a Laravel API project which connects to my portfolio and CV websites I came across an issue that needed to be resolved in Laravel 11.

The exception is output as HTML by default when calling the endpoint I was working on via the Postman application as shown below.

exception-3.png

Some code must be added to change the responses so that the API will respond with data in a JSON format.

Open the app.php file inside the bootstrap folder of the Laravel app.

You will notice the blank area inside the function within the withExceptions method call.

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Add the following new use statement to use the Request object.

use Illuminate\Http\Request;

Then add the following code below the withExceptions method call.

$exceptions->render(function (Exception $exception, Request $request) {
        if ($request->is('api/*')) {
                return response()->json(
                        [
                                'message' => $exception->getMessage()
                        ],
                        $exception->getCode() >= 400 ? $exception->getCode() : 406
                );
        }
});

This code will check if the URL has an API prefix, if it does then a JSON response will be returned with the exception message and code. If there is no code then 500 will be returned by default.

After adding the above code when recalling the endpoint in Postman it will now return the exception as a message with the correct error code.

json-response-3.png