Handle the exception and send the right response

@param GetResponseForExceptionEvent $event Event

@return void
764345
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($exception = $event->getException()) instanceof SerializationException) {
            $response = $exception->getResponse()
                ->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);

            $event->setResponse($response);
        }
    }
1173666
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $this->log = $this->logging->createLog($event->getRequest(), $event->getException()->getMessage());
    }
150743
private function handleInternalError(GetResponseForExceptionEvent $event)
    {
        if (false === $this->debug) {
            $this->logger->error($event->getException()->getMessage(), [
                'exception' => $event->getException(),
            ]);

            return;
        }

        $content = $this->templating->render('@SonataPage/internal_error.html.twig', [
            'exception' => $event->getException(),
        ]);

        $event->setResponse(new Response($content, 500));
    }
1238833
public function onConsoleException(ConsoleExceptionEvent $event)
    {
        $call = $this->callRepository->find($_REQUEST['call_id']);

        $call->setStatus(Call::STATUS_FAILED)
            ->setOutput($event->getException());

        $this->callRepository->update($call);

        $this->registerError($call);
    }
1077651
public function onException(GetResponseForExceptionEvent $event)
    {
        if ($event->isMasterRequest()) {
            return;
        }

        $exception = $event->getException();

        $level = LogLevel::CRITICAL;
        if ($exception instanceof HttpExceptionInterface && $exception->getStatusCode() < 500) {
            $level = LogLevel::WARNING;
        }

        $this->logger->log($level, $exception->getMessage(), ['event' => 'exception', 'exception' => $exception]);
    }
1244769
public function onCoreException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        $request = $event->getRequest();

        if ($request->isXmlHttpRequest()) {
            if ($exception instanceof AuthenticationException || $exception instanceof AccessDeniedException) {
                $event->setResponse(new Response('', 403));
            }
        }
    }
184976
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $request = $event->getRequest();
        $exception = $event->getException();

        if ($request->isXmlHttpRequest()) {
            if ($exception instanceof AccessDeniedException) {
                $token = $this->context->getToken();
                if (!$this->authenticationTrustResolver->isAnonymous($token)) {
                    $event->setResponse(new Response('You haven\'t enough privileges to perform the required action', 403));
                }
            }
        }
    }
243185
public function onKernelException(GetResponseForExceptionEvent $event): void
    {
        $request = $event->getRequest();

        if ($this->kernelDebug && $this->debugParameter && $request->query->has($this->debugParameter)) {
            return;
        }

        $exception = $event->getException();
        $errorPresentation = $this->errorPresentationFactory->create($exception);

        if (!$errorPresentation) {
            return;
        }

        if (!$errorPresentation->getResource()) {
            // The presentation not have resource. Send response with only status code.
            $event->setResponse(new Response('', $errorPresentation->getStatusCode()));

            return;
        }

        $acceptMediaType = null;

        try {
            $serializer = $this->serializerResolver->resolveByMediaTypes(
                get_class($errorPresentation->getResource()),
                $request->getAcceptableContentTypes(),
                $acceptMediaType
            );
        } catch (ResourceSerializerNotFoundException $e) {
            // Cannot resolve the serializer for accept media types.

            return;
        }

        $context = $this->serializationContextCollector->collect();
        $serializedData = $serializer->serialize($errorPresentation->getResource(), $context);

        $response = new Response($serializedData, $errorPresentation->getStatusCode(), [
            'Content-Type' => $acceptMediaType,
        ]);

        $event->setResponse($response);
    }
997148
public function onKernelExceptionView(GetResponseForExceptionEvent $event)
    {
        if (!$event->getRequest()->attributes->get('is_rest_request')) {
            return;
        }

        $event->setResponse(
            $this->viewDispatcher->dispatch(
                $event->getRequest(),
                $event->getException()
            )
        );
        $event->stopPropagation();
    }
950978
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if (!($event->getRequest())
            || ($this->matchAll === false && !$this->isApiException($exception))
        ) {
            return;
        }

        $data = [];

        if ($this->isApiException($exception)) {
            $exception = $this->exceptionManager->configure($exception);
        }

        $statusCode = $this->getStatusCode($exception);

        $data['error']['status']  = $statusCode;

        if ($code = $exception->getCode()) {
            $data['error']['code'] = $code;
        }

        $data['error']['message'] = $this->getMessage($exception);

        if ($this->isFlattenErrorException($exception)) {
            $data['error']['errors'] = $exception->getFlattenErrors();
        }

        if ($this->stackTrace) {
            $data['error']['stack_trace'] = $exception->getTrace();

            // Clean stacktrace to avoid circular reference or invalid type
            array_walk_recursive(
                $data['error']['stack_trace'],
                function(&$item) {
                    if (is_object($item)) {
                        $item = get_class($item);
                    } elseif (is_resource($item)) {
                        $item = get_resource_type($item);
                    }
                }
            );
        }

        $response = new JsonResponse($data, $statusCode, $this->getHeaders($exception));
        $event->setResponse($response);
    }
314793
public function onKernelException(GetResponseForExceptionEvent $event): void
    {
        $exception = $event->getException();

        if (!$exception instanceof AccessDeniedException) {
            return;
        }

        $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
    }
324550
protected function _exceptionResponse(Event $Event, $exceptionConfig)
    {
        $exceptionConfig = array_merge($this->getConfig('exception'), $exceptionConfig);

        $class = $exceptionConfig['class'];

        if ($exceptionConfig['type'] === 'validate') {
            $exception = new $class($Event->getSubject()->entity);
            throw $exception;
        }

        $exception = new $class($exceptionConfig['message'], $exceptionConfig['code']);
        throw $exception;
    }
617866
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        static $handling;

        if (true === $handling) {
            return;
        }

        $handling = true;

        $exception = $event->getException();
        $this->logException($exception, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()));

        $request = $event->getRequest();

        // Only for debug
        if ($this->debug) {
            return;
        }

        // Not for xml http requests
        if ($request->isXmlHttpRequest()) {
            return;
        }

        // Only for phlexible tree nodes
        if (!$request->attributes->has('siterootUrl')) {
            $siteroot = $this->siterootRequestMatcher->matchRequest($request);
            if (!$siteroot) {
                return;
            }
            $request->attributes->set('siterootUrl', $siteroot->getDefaultUrl());
        }

        $exception = $event->getException();
        if ($exception instanceof HttpException) {
            $code = $exception->getStatusCode();
        } else {
            $code = $exception->getCode();
        }
        if (!in_array($code, array(401, 403, 404, 500))) {
            $code = 500;
        }

        $template = null;
        if ($this->twig->getLoader()->exists("::error/error-$code.html.twig")) {
            $template = "::error/error-$code.html.twig";
        } elseif ($this->twig->getLoader()->exists('::error/error.html.twig')) {
            $template = '::error/error.html.twig';
        }

        $tid = $siteroot->getSpecialTid($request->getLocale(), "error_$code");

        if (!$tid) {
            if (!$template) {
                return;
            }

            $content = $this->twig->render($template);
            $response = new Response($content, $code);

            $event->setResponse($response);

            return;
        }

        $treeNode = $this->treeManager->findByTreeId($tid)->get($tid);

        $request = $this->duplicateRequest($exception, $request, $tid, $treeNode, $template);

        try {
            $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false);
        } catch (\Exception $e) {
            $this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), false);

            $wrapper = $e;

            while ($prev = $wrapper->getPrevious()) {
                if ($exception === $wrapper = $prev) {
                    throw $e;
                }
            }

            $prev = new \ReflectionProperty('Exception', 'previous');
            $prev->setAccessible(true);
            $prev->setValue($wrapper, $exception);

            throw $e;
        }

        $event->setResponse($response);

        return;

        $configuration = $this->configurator->configure($request);
        if ($configuration->hasResponse()) {
            $event->setResponse($configuration->getResponse());

            return;
        }

        $data = $configuration->getVariables();
        $content = $this->twig->render($data['template'], $data);
        $response = new Response($content, $code);

        $event->setResponse($response);
    }
954802
private function handleException(\Exception $exception, Request $request, $type)
    {
        $event = new GetResponseForExceptionEvent($this, $request, $type, $exception);
        $this->application->getEventDispatcher()->dispatch(KernelEvents::EXCEPTION, $event);

        return $event->getResponse();
    }
897664
public function onException(GetResponseForExceptionEvent $event): void
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        $attributes = $event->getRequest()->attributes;
        if ($attributes->get(SetIsApiRequestListener::API_FLAG_NAME) !== true) {
            return;
        }

        $exception = $event->getException();
        if ($exception instanceof HttpExceptionInterface) {
            return;
        }

        $exceptionClass = null;
        foreach ($this->exceptionMap as $sourceException => $targetException) {
            if (is_a($exception, $sourceException, true)) {
                $exceptionClass = $targetException;

                break;
            }
        }

        if ($exceptionClass !== null) {
            $convertedException = new $exceptionClass(
                $exception->getMessage(),
                $exception,
                $exception->getCode()
            );

            $event->setException($convertedException);
        }
    }
40691
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) { // don't do anything if it's not the master request

            return;
        }

        // We get the exception object from the received event
        $exception = FlattenException::create($event->getException());

        // We get the request
        $request = $event->getRequest();

        // Process the exception
        return $this->logException($exception, $request);
    }
1184894
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($exception = $event->getException()) instanceof RecordOriginModifiedException) {
            $content = array(
                "propertyPath" => "recordOrigin",
                "message"      => $exception->getMessage(),
            );

            // Set status code and content
            $response = new Response();
            $response
                ->setStatusCode($exception->getStatusCode())
                ->setContent(
                    $this->getSerializedContent($content)
                );

            $event->setResponse($response);
        }
    }