Created
September 26, 2023 10:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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