0
  • 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 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

In symfony 4+ you also need to add $event->allowCustomResponseCode();
Here I wrote article How we carried out by Listener medium.com/@mukhiddin-jumaniyazov/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.