Real Dreams
Real Dreams

Reputation: 18038

How prevent JSON exception

Laravel (5.5) apparently return the exception in json format instead of whoop page. Where can I disable this annoying behaviour and receive the whoops or the default php exception format?

Upvotes: 1

Views: 129

Answers (1)

Lionel Chan
Lionel Chan

Reputation: 8079

When you make a request that expects a JSON response, it will give you a JSON response. The following headers trigger a JSON response:

X-Requested-With: XMLHttpRequest

OR

X-PJAX: true

OR

Accept: */json or *+json

If you do not want this standard behaviour, you can overwrite your exception handler at app/Exceptions/Handler.php. Change the render function to this (this is a direct copy from vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php, and always return whoops by neglecting the request header)

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if (method_exists($e, 'render') && $response = $e->render($request)) {
        return Router::toResponse($request, $response);
    } elseif ($e instanceof Responsable) {
        return $e->toResponse($request);
    }

    $e = $this->prepareException($e);

    if ($e instanceof HttpResponseException) {
        return $e->getResponse();
    } elseif ($e instanceof AuthenticationException) {
        return $this->unauthenticated($request, $e);
    } elseif ($e instanceof ValidationException) {
        return $this->convertValidationExceptionToResponse($e, $request);
    }

    return $this->prepareResponse($request, $e);
}

Or, add your own logic here to decide what kind of content you would like to return when different headers were given.

Upvotes: 1

Related Questions