Skip to content

Instantly share code, notes, and snippets.

@JustSteveKing
Last active September 8, 2023 15:03
Show Gist options
  • Save JustSteveKing/80859db948698084593f1006735c1636 to your computer and use it in GitHub Desktop.
Save JustSteveKing/80859db948698084593f1006735c1636 to your computer and use it in GitHub Desktop.
Handling Errors in Laravel
<?php
declare(strict_types=1);
namespace App\Exceptions\Rendering;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
use Treblle\ApiResponses\Data\ApiError;
use Treblle\ApiResponses\Responses\ErrorResponse;
use Treblle\ErrorCodes\Enums\ErrorCode;
final class ApiRenderer
{
public function map(Throwable $exception, Request $request): Responsable
{
$error = match (true) {
$exception instanceof NotFoundHttpException => ErrorCode::NOT_FOUND,
default => ErrorCode::INTERNAL_SERVER_ERROR
};
return new ErrorResponse(
data: new ApiError(
title: $error->getDescription()->title,
detail: $exception->getMessage(),
instance: $request->url(),
code: $error->getDescription()->code,
link: $error->getDescription()->link,
),
status: Status::from(
value: $error->getDescription()->status,
),
);
}
}
<?php
declare(strict_types=1);
namespace App\Exceptions;
use App\Exceptions\Rendering\ApiRenderer;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
final class Handler extends ExceptionHandler
{
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
public function render($request, Throwable $e): Response
{
return (new ApiRenderer())->map(
exception: $e,
request: $request,
)->toResponse(
request: $request,
);
}
public function register(): void
{
$this->reportable(function (Throwable $e): void { });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment