Skip to content

Commit

Permalink
Send JSON in debug mode if the request wants JSON.
Browse files Browse the repository at this point in the history
Currently, when making AJAX requests with debug mode enabled, uncaught
exceptions will display the full debug HTML page. With this change, the
exceptions will be rendered as JSON for easier viewing in the console /
dev tools.
  • Loading branch information
taylorotwell committed Apr 2, 2017
1 parent a1226cb commit 5225389
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions src/Illuminate/Foundation/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ public function render($request, Exception $e)
return $this->convertValidationExceptionToResponse($e, $request);
}

if ($request->expectsJson() && config('app.debug')) {
return $this->prepareJsonResponse($request, $e);
}

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

Expand Down Expand Up @@ -166,7 +170,7 @@ protected function convertValidationExceptionToResponse(ValidationException $e,
}

/**
* Prepare response containing exception render.
* Prepare a response for the given exception.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
Expand All @@ -178,14 +182,38 @@ protected function prepareResponse($request, Exception $e)
return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
}

$e = $this->isHttpException($e)
? $e : new HttpException(500, $e->getMessage());
if (! $this->isHttpException($e)) {
$e = new HttpException(500, $e->getMessage());
}

return $this->toIlluminateResponse(
$this->renderHttpException($e), $e
);
}

/**
* Prepare a JSON response for the given exception.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function prepareJsonResponse($request, Exception $e)
{
$status = $this->isHttpException($e) ? $e->getStatusCode() : 500;

$headers = $this->isHttpException($e) ? $e->getHeaders() : [];

return response(json_encode([
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), $status, array_merge($headers, [
'Content-Type' => 'application/json'
]));
}

/**
* Render the given HttpException.
*
Expand Down

0 comments on commit 5225389

Please sign in to comment.