Skip to content

Instantly share code, notes, and snippets.

@marufmax
Last active December 17, 2018 10:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marufmax/b299b053fb5c0a82001aaeb3d0afd87c to your computer and use it in GitHub Desktop.
Save marufmax/b299b053fb5c0a82001aaeb3d0afd87c to your computer and use it in GitHub Desktop.
Laravel/Lumen API Error Handleing
<?php
/**
* 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 ($request->wantsJson()) {
$response = [
'message' => (string) $exception->getMessage(),
'status' => 400
];
if ($exception instanceof HttpException) {
$response['message'] = Response::$statusTexts[$exception->getStatusCode()];
$response['status'] = $exception->getStatusCode();
}
if ($this->isDebugMode()) {
$response['debug'] = [
'exception' => get_class($exception),
'trace' => $exception->getTrace()
];
}
return response()->json(['error' => $response], $response['status']);
}
return parent::render($request, $exception);
}
/**
* Determine if the application is debug mode
*
* @return boolean
*/
public function isDebugMode() : boolean
{
return (Boolean) env('APP_DEBUG');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment