Laravel 8 return all exceptions as json

Viewed 6554

I´m trying to get all exceptions as jsons instead of the HTML that Laravel normally returns, but i cant get it to work in Laravel 8.

I found someone who did it in Laravel 5 with the following code in /app/Exceptions/handler.php

public function render($request, Exception $exception)
{
    return response(['error'=>$exception->getMessage()], $exception->getCode() ?: 400);
}

I found this thread where they explain how to get a custom exception to return as a json, but i cant get it to work for all exceptions.

I tried doing something like this:

public function register()
{
   $this->renderable(function (Exception $e, $request) {
    return response()->json('errors.custom', [], 500);
});
}

The exception that I'm testing it with is Route [login] not defined. but it still returns the HTML

3 Answers

As @apokryfos pointed out I was asking the wrong question, putting Accept: application/json as a header in the request is all you need to receive the response as a json

Using renderable instead of reportable method in your exception Handler.php will help you return custom error message in any format you like https://laravel.com/docs/8.x/errors#renderable-exceptions. Below is an example. In your \App\Exceptions\Handler.php register method, put the following code;

public function register()
    {
        // reportable
        $this->renderable(function (Throwable $e) {
            //
            return response(['error' => $e->getMessage()], $e->getCode() ?: 400);
        });
    }

On top of that you also need to change Kernel.php file to use the \Illuminate\Auth\Middleware\Authenticate::class instead of the default \App\Http\Middleware\Autheticate::class to return the actually error and not Route [login] not defined which happens when laravel tries to redirect unauthorized routes to login route. Here is the example;

> protected $routeMiddleware = [ 
>         'auth' => \Illuminate\Auth\Middleware\Authenticate::class, // remove the \App\Http\Middleware\Authenticate::class
>         'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
>         'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
>         'can' => \Illuminate\Auth\Middleware\Authorize::class,
>         'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
>         'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
>         'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
>         'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
>         'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
>     ];
Related