When i throw an Http exception in my crud API, to avoid that symfony returns the complete error stack trace, i handle the exception with this listener:
class ExceptionListener implements EventSubscriberInterface
{
public function onKernelException(ExceptionEvent $event): void
{
// You get the exception object from the received event
$exception = $event->getThrowable();
$message = sprintf(
'My Error says: %s with code: %s',
$exception->getMessage(),
$exception->getCode()
);
// Customize your response object to display the exception details
$response = new JsonResponse(['error' => $message]);
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->set( 'X-Status-Code', $exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
// sends the modified response object to the event
$event->setResponse($response);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => ['onKernelException', 256],
];
}
}
So on Postman i can see
{
"error": "My Error says: Invalid body format with code: 0"
}
instead of the error stacktrace in html, but the status code remains 200.
Can you help me?
With xdebug i’ve seen that $response->statusCode is correctly setted to 400.
My service.yaml
AppEventListenerExceptionListener:
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }