Skip to content

Commit

Permalink
always use exception listener
Browse files Browse the repository at this point in the history
  • Loading branch information
chriskapp committed Dec 30, 2024
1 parent c2fe084 commit b6da80f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
3 changes: 2 additions & 1 deletion config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@
$services->set(PushCommand::class);

$services->set(ControllerArgumentsListener::class);
$services->set(ExceptionResponseListener::class);
$services->set(ExceptionResponseListener::class)
->arg('$debug', param('kernel.debug'));
$services->set(SerializeResponseListener::class);

};
28 changes: 19 additions & 9 deletions src/EventListener/ExceptionResponseListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,31 @@
#[AsEventListener(event: KernelEvents::EXCEPTION, method: 'onKernelException')]
final class ExceptionResponseListener
{
public function __construct(private bool $debug)
{
}

public function onKernelException(ExceptionEvent $event): void
{
$headers = [];
$exception = $event->getThrowable();
if ($exception instanceof StatusCodeException) {
$title = get_class($exception);
$message = $exception->getMessage() . ' in ' . $exception->getFile() . ' on line ' . $exception->getLine();
$trace = $exception->getTraceAsString();
$status = $exception->getStatusCode();
} else {
$status = 500;
}

$error = new Error();
$error->setSuccess(false);
$error->setTitle($title);
$error->setMessage($message);
$error->setTrace($trace);
$title = get_class($exception);
$message = $exception->getMessage() . ' in ' . $exception->getFile() . ' on line ' . $exception->getLine();

$event->setResponse(new JsonResponse($error, $exception->getStatusCode()));
$error = new Error();
$error->setSuccess(false);
$error->setTitle($title);
$error->setMessage($message);
if ($this->debug) {
$error->setTrace($exception->getTraceAsString());
}

$event->setResponse(new JsonResponse($error, $status, $headers));
}
}

0 comments on commit b6da80f

Please sign in to comment.