How can I change a Symfony exception response code

1.6k views Asked by At
  • Symfony 3.4
  • PHP 7.4

I am trying to map

Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException

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 Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException: ...

I want to return a 404 as response.

1

There are 1 answers

2
GrenierJ On BEST 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);
}