Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Haych's avatar
Level 1

Laravel API 500 Exception Issue

Hi, I'm trying to catch exceptions for my API. Everything like 400, 401, 404, etc all work fine but for 500 errors it doesnt.

$exceptions->render(function (Exception $e, Request $request) {
            if ($request->expectsJson() || $request->is('api/*')) {
                return response()->json([
                    'error' => 'Internal Server Error',
                    'message' => $e->getMessage(),
                ], 500);
            }
        });

I'm using that, but the API just returns a 500 HTML page.

If I do:

$exceptions->render(function (Exception $e, Request $request) {
                return response()->json([
                    'error' => 'Internal Server Error',
                    'message' => $e->getMessage(),
                ], 500);
        });

That works BUT any 500 errors on the web end shows JSON.

I've tried both local and production with debug mode off.

Any ideas how to get around this?

0 likes
6 replies
jdc1898's avatar

Is you .env set to local or production?

Haych's avatar
Level 1

@jdc1898 I've tried both local and production with debug mode off.

martinbean's avatar

I'm trying to catch exceptions for my API. Everything like 400, 401, 404, etc all work fine but for 500 errors it doesnt.

@haych Why? Catching exceptions is the entire point of the built-in exception handler.

By trying to catch all exceptions, all you’re doing is making your life harder as it then means the actual exception’s message and stack trace isn’t going to get logged, leaving you with nothing helpful to use to diagnose issues after they’ve occurred.

Laravel already handles uncaught exceptions. Stop trying to re-invent the wheel.

1 like
Haych's avatar
Level 1

@martinbean Because I want to return the user a consistent error message/response to the user when using the API for all requests? Why would I want to return an HTML page to them in the API..... My custom exception handler already logs the errors and passes them back to me.

The code I provided is just an example.

martinbean's avatar
Level 80

Because I want to return the user a consistent error message/response to the user when using the API for all requests?

@Haych Laravel does this already. It returns the correct HTTP status code, and presents errors using a format like:

{
    "message": "Something contextual."
}

Why would I want to return an HTML page to them in the API

You’ll get JSON responses if you request you want a JSON response, by including a Accept: application/json header in your requests.

1 like
Haych's avatar
Level 1

@martinbean That's what I was missing.

Accept: application/json

Thank you.

1 like

Please or to participate in this conversation.