Laravel how to display all HTTP error codes in JSON?

679 Views Asked by At

As I create a REST API, I want all 404 and 403 errors displayed as JSON. When I try to return a message, the message is empty, but the error codes are usually displayed. Does anyone know what I'm doing wrong? I'm using PHP 8 and Laravel 9.

use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    public function register()
    {
        $this->renderable(function (Throwable $e, $request) {
            $request->headers->set('Accept', 'application/json');

            if ($e instanceof HttpExceptionInterface && $request->wantsJson()) {
                $code = $e->getStatusCode() ?: 400;
                $message = $e->getMessage() ?: 'Invalid Request.';

                return response(['success' => false, 'message' => $message], $code);
            }
        });

        $this->reportable(function (Throwable $e) {
            //
        });
    }
}
1

There are 1 best solutions below

3
Vüsal Hüseynli On

I think you have to return response in json format like

return response()->json([
    'code' => 404
]);

and if you gonna try your api in postman do not forget to add

Accept: application/json

in headers.