Skip to content

Instantly share code, notes, and snippets.

@raulneis
Last active July 4, 2018 11:11
Show Gist options
  • Save raulneis/c984a1b60083366d5957b2b067754b62 to your computer and use it in GitHub Desktop.
Save raulneis/c984a1b60083366d5957b2b067754b62 to your computer and use it in GitHub Desktop.
<?php
class Handler extends ExceptionHandler
{
// ...
public function render($request, Exception $exception)
{
if (strpos($request->getUri(), '/api/') !== false) {
$exception = $this->prepareException($exception);
if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
return $exception->getResponse();
}
if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return $this->unauthenticated($request, $exception);
}
if ($exception instanceof \Illuminate\Validation\ValidationException) {
return $this->convertValidationExceptionToResponse($exception, $request);
}
$response = [];
if (method_exists($exception, 'getStatusCode')) {
$statusCode = $exception->getStatusCode();
} else {
$statusCode = 500;
}
switch ($statusCode) {
case 404:
$response['error'] = 'Not Found';
break;
case 403:
$response['error'] = 'Forbidden';
break;
default:
$response['error'] = $exception->getMessage();
break;
}
if (config('app.debug')) {
$response['trace'] = $exception->getTrace();
$response['code'] = $exception->getCode();
}
return response()->json($response, $statusCode);
}
return parent::render($request, $exception);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment