Last active
October 29, 2016 11:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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