Skip to content

Instantly share code, notes, and snippets.

@TiagoSilvaPereira
Created October 14, 2021 18:05
Show Gist options
  • Save TiagoSilvaPereira/8d34c790a96e5093c3fdb58433894a7c to your computer and use it in GitHub Desktop.
Save TiagoSilvaPereira/8d34c790a96e5093c3fdb58433894a7c to your computer and use it in GitHub Desktop.
Laravel Exception Handler for API
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* @param \Throwable $exception
* @return void
*
* @throws \Exception
*/
public function report(Throwable $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render($request, Throwable $exception)
{
if ($request->is('api/*')) {
return $this->processApiException($request, $exception);
}
return parent::render($request, $exception);
}
protected function processApiException($request, $exception)
{
$errorStatus = method_exists($exception, 'getStatusCode') ? $exception->getStatusCode() : 500;
$errorResponse = [
'message' => $exception->getMessage() ?: 'Something went wrong',
'trace' => app()->environment() == 'local' ? $exception->getTrace() : null,
'errors' => method_exists($exception, 'errors') ? $exception->errors() : [],
];
if ($exception instanceof \Illuminate\Validation\ValidationException) {
$errorStatus = 422;
}
if ($exception instanceof \Illuminate\Auth\AuthenticationException ||
$exception instanceof \Illuminate\Auth\Access\AuthorizationException) {
$errorStatus = 401;
}
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
$errorStatus = 404;
}
$errorResponse['status'] = $errorStatus;
return response()->json($errorResponse, $errorStatus);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment