如何更改Symfony异常响应代码

问题描述

  • Symfony 3.4
  • PHP 7.4

我正在尝试地图

Symfony\Component\HttpFoundation\Exception\SuspicIoUsOperationException

一个响应代码。基本上像Laravel一样:https://github.com/laravel/framework/pull/29000/files

当前它会产生致命错误并响应500:

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

我想返回一个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);
}