Skip to content

Instantly share code, notes, and snippets.

@tanner0101
Last active October 29, 2016 11:08
Show Gist options
  • Save tanner0101/cb2d981a3cfeabd425b8 to your computer and use it in GitHub Desktop.
Save tanner0101/cb2d981a3cfeabd425b8 to your computer and use it in GitHub Desktop.
Use this exception handle for your Laravel 5 based JSON APIs. It serves properly formatted JSON responses instead of the default Laravel HTML error pages.
<?php
/**
* LaravelExceptionHandler.php
*
* Use this exception handle for your Laravel 5 based JSON APIs.
* It serves properly formatted JSON responses instead of the default Laravel HTML error pages.
*
* <https://gist.github.com/tannernelson/cb2d981a3cfeabd425b8>
*/
public function render($request, Exception $e)
{
//return parent::render($request, $e);
if($e instanceof HttpException) {
$message = $e->getMessage();
$code = $e->getStatusCode();
if ($message == '') {
switch($code) {
case 401:
$message = 'Invalid authorization';
break;
case 403:
$message = 'Insufficient authorization';
break;
case 404:
$message = 'Resource not found';
break;
case 405:
$message = 'Method ' . $request->method() . ' is not supported on this route';
break;
case 503:
$message = 'Be right back';
break;
default:
$message = 'Something went wrong';
}
}
return response()->json([
'message' => $message,
'error' => true
], $code);
} else {
$response = [
'message' => 'Something went wrong',
'error' => true,
];
if (debug()) {
$response['debug'] = [
'message' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile()
];
}
return response()->json($response, 500);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment