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

KarolGil's avatar

Returning an error in JSON instead of 500

Hi,

Can you write general error returns? Ie. that Laravel instead of returning 500 error should be returned in JSON format. Regardless of where in the code the error occurs.

0 likes
2 replies
KarolGil's avatar

@armancodes Could you write me a cover how to choose to look or send a link with a tutorial?

Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@karolgil yes, you can do that in render method in your app/Exceptions/Handler.php file.

This would return a custom JSON response for all exceptions:

public function render($request, Exception $exception)
{
   return response()->json([
      'type' => get_class($exception),
      'message' => $exception->getMessage()
   ]);
}
{
  "type": "Symfony\Component\Debug\Exception\FatalThrowableError",
  "message": "Class 'TestClass' not found"
}
{
  "type": "Illuminate\Database\Eloquent\ModelNotFoundException",
  "message": "No query results for model [App\User] 100"
}

https://laravel.com/docs/7.x/errors#render-method

1 like

Please or to participate in this conversation.