Exception handler return in JSON

2

I am building a RestAPI using Laravel / Lumen , in tests it can happen that the return is entirely in HTML, this occurs when that already famous screen appears: Whoops looks like something went wrong

This is very difficult to test the rest, and can never happen in the production environment, how can I make that return be in Json?

    
asked by anonymous 24.01.2017 / 00:50

1 answer

1

Just change the exception handler from the framework , located at app\Exceptions\Handler.php , changing the method that renders exceptions, leaving it like this:

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

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

Basically every time an exception occurs you are getting some data, such as error code and its message, and returning in JSON . In the production environment this would never appear, since you disable 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 that case only when the error code is nonzero, because the zero error refers to the validation error, then the code looks 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);
}
    
24.01.2017 / 00:50