Handles a native error.

@param GetResponseForExceptionEvent $event

@throws mixed
778575
private function handleNativeError(GetResponseForExceptionEvent $event)
    {
        if (true === $this->debug) {
            return;
        }

        if (true === $this->status) {
            return;
        }

        $this->status = true;

        $exception = $event->getException();
        $statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;

        $cmsManager = $this->cmsManagerSelector->retrieve();

        if ($event->getRequest()->get('_route') && !$this->decoratorStrategy->isRouteNameDecorable($event->getRequest()->get('_route'))) {
            return;
        }

        if (!$this->decoratorStrategy->isRouteUriDecorable($event->getRequest()->getPathInfo())) {
            return;
        }

        if (!$this->hasErrorCode($statusCode)) {
            return;
        }

        $message = sprintf('%s: %s (uncaught exception) at %s line %s', \get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine());

        $this->logException($exception, $exception, $message);

        try {
            $page = $this->getErrorCodePage($statusCode);

            $cmsManager->setCurrentPage($page);

            if (null !== $page->getSite()->getLocale() && $page->getSite()->getLocale() !== $event->getRequest()->getLocale()) {
                // Compare locales because Request returns the default one if null.

                // If 404, LocaleListener from HttpKernel component of Symfony is not called.
                // It uses the "_locale" attribute set by SiteSelectorInterface to set the request locale.
                // So in order to translate messages, force here the locale with the site.
                $event->getRequest()->setLocale($page->getSite()->getLocale());
            }

            $response = $this->pageServiceManager->execute($page, $event->getRequest(), [], new Response('', $statusCode));
        } catch (\Exception $e) {
            $this->logException($exception, $e);

            $event->setException($e);
            $this->handleInternalError($event);

            return;
        }

        $event->setResponse($response);
    }
1122788
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($event->getException() instanceof NotFoundHttpException && $this->cmsManagerSelector->isEditor()) {
            $pathInfo = $event->getRequest()->getPathInfo();

            // can only create a CMS page, so the '_route' must be null
            $creatable = !$event->getRequest()->get('_route') && $this->decoratorStrategy->isRouteUriDecorable($pathInfo);

            if ($creatable) {
                $response = new Response($this->templating->render('@SonataPage/Page/create.html.twig', [
                    'pathInfo' => $pathInfo,
                    'site' => $this->siteSelector->retrieve(),
                    'creatable' => $creatable,
                ]), 404);

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

                return;
            }
        }

        if ($event->getException() instanceof InternalErrorException) {
            $this->handleInternalError($event);
        } else {
            $this->handleNativeError($event);
        }
    }
784246
public function handleException($exception)
	{
		$response = $this->callCustomHandlers($exception);

		// If one of the custom error handlers returned a response, we will send that
		// response back to the client after preparing it. This allows a specific
		// type of exceptions to handled by a Closure giving great flexibility.
		if ( ! is_null($response))
		{
			$response = $this->prepareResponse($response);
		}

		// If no response was sent by this custom exception handler, we will call the
		// default exception displayer for the current application context and let
		// it show the exception to the user / developer based on the situation.
		else
		{
			$response = $this->displayException($exception);
		}

		return $this->sendResponse($response);
	}
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);
    }
191463
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($exception = $event->getException()) instanceof ValidationException) {
            $content = $this->getErrorMessages($exception->getErrors());
            // Set status code and content
            $response = new Response();
            $response
                ->setStatusCode(Response::HTTP_BAD_REQUEST)
                ->setContent(
                    $this->getSerializedContent($content)
                );

            $event->setResponse($response);
        }
    }
262136
public function handleDevelopmentError(SystemEvent $systemEvent, $exception)
    {
        $details = [];

        $e = $exception;
        while ($e) {
            $item = [
                'class'   => get_class($exception),
                'message' => $exception->getMessage(),
                'file'    => $exception->getFile(),
                'line'    => $exception->getLine(),
                'trace'   => $exception->getTraceAsString(),
            ];

            $details[] = $item;
            $e         = $e->getPrevious();
        }
        $result = json_encode(['details' => $details]);
        $body   = Stream::make($result);

        $status = 503;

        if ($exception instanceof ExceptionInterface && $exception->getCode()) {
            $status = $exception->getCode();
        }
        $response = new Response($status, $body, ['Content-Type' => 'application/problem+json']);
        $this->processResponse($response, $systemEvent);
    }
1210577
public function isNotFoundException(GetResponseForExceptionEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return false;
        }

        $exception = $event->getException();

        if (!$exception instanceof HttpException || 404 !== (int) $exception->getStatusCode()) {
            return false;
        }

        return true;
    }
613917
private function setNewResponse(GetResponseForExceptionEvent $event, $statusCode, $message = '')
    {
        $event->setResponse(new Response());
        $event->getResponse()->setStatusCode($statusCode, $message);
    }
1037989
public function onKernelException(GetResponseForExceptionEvent $e)
    {
        if (!$this->enabled) return;

        $req = $e->getRequest();
        $cfg = $req->attributes->get('_ac_web_service');

        //notify of generic API error, return early if a response gets set
        $e->getDispatcher()->dispatch(self::API_EXCEPTION, $e);
        if ($e->getResponse()) {
            return;
        }

        //handle exception body format
        $exception = $e->getException();
        $exceptionClass = get_class($exception);

        //preserve specific http exception codes and messages, otherwise it's 500
        $realHttpErrorCode = $outgoingHttpStatusCode = 500;
        $errorMessage = "Internal Server Error";
        if ($exception instanceof ServiceException) {
            $errorData = $exception->getData();
        }
        if ($exception instanceof HttpException) {
            $realHttpErrorCode = $outgoingHttpStatusCode = $exception->getStatusCode();
            $errorMessage = ($exception->getMessage()) ? $exception->getMessage() : Response::$statusTexts[$realHttpErrorCode];
        } elseif (isset($cfg['http_exception_map'][$exceptionClass])) {
            //check exception map for overrides
            $map = $cfg['http_exception_map'];
            $realHttpErrorCode = $outgoingHttpStatusCode = $map[$exceptionClass]['code'];
            $errorMessage =
                (isset($map[$exceptionClass]['message']))
                ? $map[$exceptionClass]['message']
                : Response::$statusTexts[$realHttpErrorCode];
        }

        //set generic error data
        if (!isset ($errorData)) {
            $errorData = [];
        }
        $errorData['response'] = [
            'code' => $realHttpErrorCode,
            'message' => $errorMessage,
        ];

        //inject exception data if configured to do so
        if ($cfg['include_exception_data']) {
            $errorData['exception'] = array(
                'class' => get_class($exception),
                'message' => $exception->getMessage(),
                'code' => $exception->getCode(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => explode("\n", ImprovedStackTrace::getTrace($exception)),
            );
        }

        //serialize error content into requested format, if format is not supported by the serializer, do json
        //TODO: consider support for exception template formats
        $format = isset($cfg['http_response_format']) ? $cfg['http_response_format'] : $cfg['default_response_format'];
        $format = (in_array($format, $this->serializableFormats)) ? $format : 'json';
        $content = $this->container->get('serializer')->serialize($errorData, $format);

        //check for code suppression
        if ($cfg['suppress_response_codes']) {
            $outgoingHttpStatusCode = 200;
        }

        //log the exception
        $logLevel = $realHttpErrorCode >= 500 ? 'error' : 'warning';
        $logMessage =
            "Caught exception (mapped to code $realHttpErrorCode), " .
            "response to client becomes HTTP $outgoingHttpStatusCode $errorMessage\n" .
            ImprovedStackTrace::getTrace($exception) . "\n---";
        $this->logger->log($logLevel, $logMessage);

        $headers = array_merge($cfg['additional_headers'], $this->formatHeaders[$format]);

        //set response
        $e->setResponse(new Response($content, $outgoingHttpStatusCode, $headers));
    }
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);
        }
    }
175846
private function determineErrorResponse(
        $exception,
        $message,
        ResponseInterface $response,
        ServerRequestInterface $request
    )
    {
        $applicationEvent = $this->getApplicationEvent();
        $applicationEvent->setName(self::EVENT_LIFECYCLE_ERROR);
        $applicationEvent->setRequest($request);
        $applicationEvent->setResponse($response);
        $applicationEvent->setErrorResponse($this->getResponse());

        $this->emit($applicationEvent, $exception);

        $errorResponse = $applicationEvent->getErrorResponse();

        if (!$errorResponse->getBody()->isWritable()) {
            return $errorResponse;
        }

        $content = $errorResponse->getBody()->__toString();
        if (empty($content)) {
            $errorResponse->getBody()->write($message);
        }

        return $errorResponse;
    }
316449
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        if ($exception instanceof HttpException) {
            return;
        }
        $culprit = null;
        if ($event->getRequest()->attributes->has("_controller")) {
            $culprit = $event->getRequest()->attributes->get("_controller");
        }
        $event_id = $this->client->getIdent($this->client->captureException($exception, $culprit, $this->client->getEnvironment()));

        return error_log("[$event_id] " . $exception->getMessage() . ' in: ' . $exception->getFile() . ':' . $exception->getLine());
    }
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));
    }
1241360
public function onException(FilterExceptionEvent $event)
    {
        static $handling;

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

        $handling = true;

        $exception = $event->getException();
        $request   = $event->getRequest();

        // This would be where we'd log, make another method that checks if logger is there and logs.

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

        try {
            $response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST);
        } catch (\Exception $e) {
            // Log exception being thrown when trying to handle an exception.

            // Set handling to false otherwise it wont be able to handle further more
            $handling = false;

            // Re-throw the exception from within the kernel.
            throw $e;
        }

        $event->setResponse($response);

        $handling = false;
    }
490047
public function handle(GetResponseEvent $event): void
    {
        if ($this->isEnabled()) {
            $hostRole = $this->getHostRole($event);

            if (null !== $hostRole) {
                $this->sidManager->addSpecialRole($hostRole);
            }
        }
    }
578456
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($exception = $event->getException()) instanceof NoInputException) {
            $msg = array("message" => "No input data");

            $response = $exception->getResponse()
                ->setStatusCode(Response::HTTP_BAD_REQUEST)
                ->setContent($this->getSerializedContent($msg));

            $event->setResponse($response);
        }
    }
574773
public function redirectTrailingSlashOrHtml(GetResponseForExceptionEvent $event)
    {
        if (!$event->getException() instanceof NotFoundHttpException) {
            return;
        }

        $request = $event->getRequest();

        /** @var RequestAttributes $attributes */
        $attributes = $request->attributes->get('_sulu');
        if (!$attributes) {
            return;
        }

        $prefix = $attributes->getAttribute('resourceLocatorPrefix');
        $resourceLocator = $attributes->getAttribute('resourceLocator');

        $route = '/' . trim($prefix . $resourceLocator, '/');
        if (!in_array($request->getRequestFormat(), ['htm', 'html'])
            || $route === $request->getPathInfo()
            || !$this->matchRoute($request->getSchemeAndHttpHost() . $route)
        ) {
            return;
        }

        $event->setResponse(new RedirectResponse($route, 301));
    }