How to send Laravel error responses as JSON

Andres picture Andres · Feb 11, 2015 · Viewed 26k times · Source

Im just move to laravel 5 and im receiving errors from laravel in HTML page. Something like this:

Sorry, the page you are looking for could not be found.

1/1
NotFoundHttpException in Application.php line 756:
Persona no existe
in Application.php line 756
at Application->abort('404', 'Person doesnt exists', array()) in helpers.php line 

When i work with laravel 4 all works fine, the errors are in json format, that way i could parse the error message and show a message to the user. An example of json error:

{"error":{
"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"message":"Person doesnt exist",
"file":"C:\\xampp\\htdocs\\backend1\\bootstrap\\compiled.php",
"line":768}}

How can i achieve that in laravel 5.

Sorry for my bad english, thanks a lot.

Answer

dstick picture dstick · Aug 16, 2015

I came here earlier searching for how to throw json exceptions anywhere in Laravel and the answer set me on the correct path. For anyone that finds this searching for a similar solution, here's how I implemented app-wide:

Add this code to the render method of app/Exceptions/Handler.php

if ($request->ajax() || $request->wantsJson()) {
    return new JsonResponse($e->getMessage(), 422);
}

Add this to the method to handle objects:

if ($request->ajax() || $request->wantsJson()) {

    $message = $e->getMessage();
    if (is_object($message)) { $message = $message->toArray(); }

    return new JsonResponse($message, 422);
}

And then use this generic bit of code anywhere you want:

throw new \Exception("Custom error message", 422);

And it will convert all errors thrown after an ajax request to Json exceptions ready to be used any which way you want :-)