Exception Handler having return in JSON

Asked

Viewed 515 times

2

I’m building a Restapi using Laravel/Lumen, in tests can occur the return be totally in HTML, this occurs when it appears that already famous screen: Whoops looks like Something Went Wrong

This gets in the way of testing the Reset, and it can never happen in the production environment, as I can make this return be in Json?

1 answer

1


Just change the Handler with the exception of framework, located in app\Exceptions\Handler.php, changing the method that renders the exceptions, leaving it so:

public function render($request, Exception $e)
{
    $json = [
        'success' => false,
        'error' => [
            'code' => $e->getCode(),
            'message' => $e->getMessage(),
        ],
    ];

    return response()->json($json, 400);
}

Basically whenever an exception occurs you are picking up some data such as the error code and its message and returning in JSON. In the production environment this would never appear, as long as it disables the debug.

But note that this will also bar a request with wrong validation, and you will not be allowed to pick up the validation messages, to circumvent this we need to respond in json in this case only when the error code is non-zero, because the zero error is related to the validation error, then the code will look like this:

public function render($request, Exception $e)
{
    if($e->getCode() != 0) {
        $json = [
            'success' => false,
            'error' => [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
            ],
        ];

        return response()->json($json, 400);
    }

    return parent::render($request, $e);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.