protected function handleException(\Exception $e, $request, $type)
    {
        $event = new FilterExceptionEvent($this, $request, $type);
        $event->setException($e);

        $this->getDispatcher()->dispatch(KernelEvents::EXCEPTION, $event);

        $e = $event->getException();

        if ( ! $event->hasResponse()) {
            throw $e;
        }

        $response = $event->getResponse();

        if ( ! $response->isClientError() && ! $response->isServerError() && ! $response->isRedirect()) {
            if ($e instanceof HttpExceptionInterface) {
                $response->setStatusCode($e->getStatusCode());
                $response->headers->add($e->getHeaders());
            } else {
                $response->setStatusCode(500);
            }
        }

        try {
            return $this->filterResponse($response, $request, $type);
        } catch (\Exception $e) {
            return $response;
        }
    }