I created an exception class as follows:
<?php
declare(strict_types=1);
namespace App\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use function strpos;
final class HTTPExceptionListener
{
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getException();
if (! ($exception instanceof HttpException) || strpos($event->getRequest()->getRequestUri(), '/api/') === false) {
return;
}
$response = new JsonResponse(['error' => $exception->getMessage()]);
$response->setStatusCode($exception->getStatusCode());
$event->setResponse($response);
}
}
I have added following to my services.yaml file:
App\Exception\HTTPExceptionListener:
tags:
- { name: kernel.event_listener, event: kernel.exception }
But I am getting error:
Attempted to call an undefined method named "getException" of class "Symfony\Component\HttpKernel\Event\ExceptionEvent".
$event->getThrowable()?ExceptionEventclass and inspect its methods?getExceptionmethod, the error message is self explanatory 3) look for other methods 4) notice thegetThrowablemethod 5) usegetThrowableinstead 6) read the docs