Search code examples
phpsymfonydockersymfony4

Symfony4 Uncaught BadRequestHttpException on Docker


I create a proxy api to make a bridge between soap and rest in symfony4. In order to properly catch my soap exception I created the Listner below. Localy my soap exception are catched and thrown as BadRequestHttpException. When I deploy my code on a Docker container I have the following error: Uncaught Symfony\\Component\\HttpKernel\\Exception\\BadRequestHttpException:

There is my listner:

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());
        }
    }
}

Solution

  • In my opinion, your issue has nothing to do with Docker.

    You created a TrinityListener which is listening to kernel.exception event (a 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, so you throw a BadRequestHttpException, that's fine but the exception is not caught. That's the the issue, the error is very explicit, you should use a try...catch to fix this.

    Exception from php documentation:

    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().

    So you can fix your issue like this:

    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);
            }
        }
    }