如何更改 Symfony 异常响应代码

How can I change a Symfony exception response code

我正在尝试映射

Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException

到另一个响应代码。基本上就像 Laravel 所做的那样:https://github.com/laravel/framework/pull/29000/files

目前它会产生致命错误和 500 响应:

PHP Fatal error: Uncaught Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException: ...

我想return一个404作为回应。

如果你想像 Laravel 那样做,你应该看看 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);
}