Skip to content
Advertisement

How can I change a Symfony exception response code

  • Symfony 3.4
  • PHP 7.4

I am trying to map

SymfonyComponentHttpFoundationExceptionSuspiciousOperationException

to another response code. Basically like Laravel did: https://github.com/laravel/framework/pull/29000/files

Currently it creates a fatal error and 500 response:

PHP Fatal error: Uncaught SymfonyComponentHttpFoundationExceptionSuspiciousOperationException: ...

I want to return a 404 as response.

Advertisement

Answer

If you want to do like in Laravel, you should take a look at Event Listener.

public function onKernelException(ExceptionEvent $event)
{
    // You get the exception object from the received event
    $exception = $event->getThrowable();
    
    // Customize your response object to display the exception details
    $response = new Response();

    if ($exception instanceof SuspiciousOperationException) {
        $response->setStatusCode(404);
    } else {
        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
    }

    // sends the modified response object to the event
    $event->setResponse($response);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement