Docker 上的 Symfony4 未捕获 BadRequestHttpException

Symfony4 Uncaught BadRequestHttpException on Docker

我创建了一个代理 api 来在 symfony4 中搭建 soap 和 rest 之间的桥梁。为了正确捕获我的 soap 异常,我在下面创建了 Listner。本地我的 soap 异常被捕获并作为 BadRequestHttpException 抛出。当我在 Docker 容器上部署代码时出现以下错误:Uncaught Symfony\Component\HttpKernel\Exception\BadRequestHttpException:

有我的听众:

class TrinityListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::EXCEPTION => array('onKernelException', -64),
        );
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($e = $event->getException()) instanceof \SoapFault) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}

我认为您的问题与Docker无关。

您创建了一个 TrinityListener,它正在侦听 kernel.exception 事件(一个 GetResponseForExceptionEvent object actually). When this event occurs the onKernelException method is executed and it is unusual to throw an exception here without catching it properly. Your initial exception is an instance of \SoapFault,所以您抛出BadRequestHttpException,没问题,但没有捕获到异常。这就是问题所在,错误非常明显,你应该使用 try...catch 来解决这个问题。

Exception 来自 php 文档:

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

所以你可以这样解决你的问题:

class TrinityListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::EXCEPTION => array('onKernelException', -64),
        );
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        try {
            if (($e = $event->getException()) instanceof \SoapFault) {
                throw new BadRequestHttpException($e->getMessage());
            }
        } catch (BadRequestHttpException $e) {
            $response = new Response();
            $message = sprintf(
                'Error %s with code: %s',
                $exception->getMessage(),
                $exception->getCode()
            );
            $response->setContent($message);
            $response->setStatusCode($exception->getStatusCode());
            $event->setResponse($response);
        }
    }
}

下面的方法做同样的事情更轻松:

public function onKernelException(GetResponseForExceptionEvent $event)
{
    if ($event->getException() instanceof \SoapFault) {
        $response = new Response();
        $response->setStatusCode(Response::HTTP_BAD_REQUEST);
        $response->setContent($event->getException()->getMessage());
        $event->setResponse($response);
    }
}