Skip to content

Instantly share code, notes, and snippets.

@juslintek
Created September 26, 2023 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juslintek/9cc283abcb74c5c87b126da189729bb4 to your computer and use it in GitHub Desktop.
Save juslintek/9cc283abcb74c5c87b126da189729bb4 to your computer and use it in GitHub Desktop.
Allows to passover exception that is derivative of ApiException its message and code as response code and error payload
<?php
use Illuminate\Http\JsonResponse;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<Throwable>>
*/
protected $dontReport = [
\Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class,
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register(): void
{
}
public function render($request, Throwable $exception)
{
// Custom handling logic
if ($exception instanceof ApiException) {
$code = $exception->getCode();
$message = $exception->getMessage();
// Modify response based on code and message
if ($code > 400 && $code < 600) {
return new JsonResponse(['error' => $message], $code);
}
}
return parent::render($request, $exception);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment