Marlon Buendia
Marlon Buendia

Reputation: 342

How to store error exception in a variable and return as json

Im working with an API used by Android Development. My Framework: Laravel 4.2 and PHP: PHP5.6

I already found a library but couldn't make it work: https://github.com/Radweb/JSON-Exception-Formatter

My problem, I have this error exception (attached images) enter image description here

I can't see it properly in Mobile, it just crashes. Im using https://www.getpostman.com/ for testing my API.

What I wanted to do is return this error exception as json so that the android can catch it.

{ "status" : "fail", "messsage" : "syntax error, unexpected 's'(T_STRING), expecting ']'", "file" : "/app/controller/v1/UserController.php", "line" : "31" }

Upvotes: 0

Views: 427

Answers (1)

henrik
henrik

Reputation: 1618

To make Laravel 4 output exceptions as JSON, one could simply edit the global.php as described in this article: http://fideloper.com/error-handling-with-content-negotiation

So in your app/start/global.php do something like this:

use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

App::error(function(HttpExceptionInterface $exception, $code)
{

    if ( Request::header('accept') === 'application/json' )
    {
        return Response::json([
            'error' => true,
            'message' => $exception->getMessage(),
            'code' => $code],
            $code
        );
    }

});

Upvotes: 1

Related Questions