Determines response for error. Emits `lifecycle.error` event.

@param \Throwable $exception
@param string $message
@param ResponseInterface $response
@param ServerRequestInterface $request
@return ResponseInterface
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;
    }
445410
private function processError(ServerRequestInterface $request, ResponseInterface $response, array $arguments = null)
    {
        if (is_callable($this->options["error"])) {
            $handler_response = $this->options["error"]($request, $response, $arguments);
            if (is_a($handler_response, "\Psr\Http\Message\ResponseInterface")) {
                return $handler_response;
            }
        }
        return $response;
    }
1061274
protected function errorResponse(Request $request, \Exception $exception): JsonResponse
    {
        if ($exception instanceof EntryNotFoundException || $exception instanceof SectionNotFoundException) {
            $statusCode = JsonResponse::HTTP_NOT_FOUND;
        } else {
            $statusCode = JsonResponse::HTTP_BAD_REQUEST;
        }
        return new JsonResponse([
            'error' => $exception->getMessage()
        ], $statusCode, $this->getDefaultResponseHeaders($request));
    }
583280
protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $response)
    {
        if ($command instanceof ScriptCommand && $response->getErrorType() === 'NOSCRIPT') {
            $eval = $this->createCommand('EVAL');
            $eval->setRawArguments($command->getEvalArguments());

            $response = $this->executeCommand($eval);

            if (!$response instanceof ResponseInterface) {
                $response = $command->parseResponse($response);
            }

            return $response;
        }

        if ($this->options->exceptions) {
            throw new ServerException($response->getMessage());
        }

        return $response;
    }
883384
private function issueResponse(Request $request, \Exception $exception = null)
    {
        $responder = null;
        if ($exception === null) {
            // No exception, just return a normal responder.
            $responder = ResponderFactory::getResponder($request);
        } else {
            // Any type of exception, just find an error responder.
            $responder = ResponderFactory::getErrorResponder($request, $exception);
        }
        // The responder is asked to produce a Response object, which is then
        // asked to perform whatever actions it takes to issue the response.

        try {
            $response = $responder->getResponse();
        } catch (NotAuthenticatedException $exception) {
            // A resource that needs authentication was hit.

            // Store the current locator, to be able to return to it after
            // signing in.
            $this->keepCurrentLocator($request);
            // Request identification from the user.
            // Set the method to GET for the identity request. POST is reserved
            // for the actual posting of the identity data by the user.
            $request->setMethod(HttpRequest::HTTP_METHOD_GET);
            $responder = new IdentityResponder($request);
            $response = $responder->getResponse();
        }

        if ($response instanceof Response) {
            // Provide a hook for last-minute response work.
            $this->alterResponse($response);
            // Issue the response.
            $response->issue();
        } else {
            throw new HttpException('No response available.');
        }
    }
584978
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $result = $request->getAttribute('routing');

        if (isset($result['error'])) {
            throw HttpErrorException::create($result['error'], [
                'code' => $result['error'],
                'message' => 'Routing not found',
            ]);
        }

        $this->count = 0;
        $this->app->setRequest($request->withoutAttribute('routing'));

        return $this->handle($result['handler'], $result['params']);
    }
215187
private function createResponseForFailedRequest(Request $request, \Throwable $exception): Response
    {
        $code = $exception->getCode() > 0 ? $exception->getCode() : Code::UNKNOWN;

        $response = RequestFailedResponseV1::create()
            ->set('ctx_request_ref', $request->generateMessageRef())
            ->set('ctx_request', $request)
            ->set('error_code', $code)
            ->set('error_name', ClassUtils::getShortName($exception))
            ->set('error_message', substr($exception->getMessage(), 0, 2048))
            ->set('stack_trace', $exception->getTraceAsString());

        if ($exception->getPrevious()) {
            $response->set('prev_error_message', substr($exception->getPrevious()->getMessage(), 0, 2048));
        }

        if ($request->has('ctx_correlator_ref')) {
            $response->set('ctx_correlator_ref', $request->get('ctx_correlator_ref'));
        }

        return $response;
    }
378693
protected function handleErrorResponse(Response $response)
    {
        $exception = $response->exception;

        $error = new MessageBag([
            'type'    => get_class($exception),
            'message' => $exception->getMessage(),
            'file'    => $exception->getFile(),
            'line'    => $exception->getLine(),
        ]);

        return back()->withInput()->withErrors($error, 'exception');
    }
652646
protected function handlePhpError(Throwable $e, ServerRequestInterface $request, ResponseInterface $response)
    {
        $handler = 'phpErrorHandler';
        $params = [$request, $response, $e];

        if ($this->container->has($handler)) {
            $callable = $this->container->get($handler);
            // Call the registered handler
            return call_user_func_array($callable, $params);
        }

        // No handlers found, so just throw the exception
        throw $e;
    }
1189793
public function handleException(ServerRequestInterface $request, ResponseInterface $response, Exception $exception)
    {
        return $this->withError($response, $exception);
    }
731932
private function defaultErrorHandler(
        ServerRequestInterface $request,
        ResponseInterface $response
    ) {
        $response = $response->withStatus(422, 'Unprocessable Entity')
            ->withHeader('Content-Type', 'application/json');

        $middlewareAttribute = $request->getAttribute(Middleware::KEY, []);

        if (isset($middlewareAttribute[self::KEY])) {
            /** @var ResponseInterface $response */
            $stream = $response->getBody();
            $stream->write(json_encode($middlewareAttribute[self::KEY], JSON_UNESCAPED_SLASHES));
        }

        return $response;
    }
1177787
protected function genericResponse(Exception $exception): Response
    {
        $replacements = $this->prepareReplacements($exception);

        return new Response($replacements, $this->getHttpStatusCode($exception), $this->getHeaders($exception));
    }
67434
public function serverError(\Throwable $exception, ServerRequestInterface $request) : ResponseInterface
    {
        $this->exception = $exception;

        $acceptType = $request->getHeader('Accept');
        if (is_array($acceptType) && count($acceptType) > 0 && strpos($acceptType[0], 'json') !== false) {
            return new JsonResponse(['error' => ['message' => $exception->getMessage(), 'type' => 'Exception', 'trace' => $this->debugMode ? $exception->getTraceAsString() : '']], 500);
        }

        if ($this->contentFor500) {
            $this->contentBlock->addHtmlElement($this->contentFor500);
        } else {
            $this->contentBlock->addFile(__DIR__ . '/../../../../views/500.php', $this);
        }

        return HtmlResponse::create($this->template, 500);
    }
536931
public function error($exception)
    {
        $response = new Response();

        // Set the default error response
        $response->setContent('There has been a problem serving this request.');
        $response->headers->set('content-type', 'text/html');
        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);

        // Execute the user defined error callback
        if (is_callable($this->error)) {
            $response = call_user_func($this->error, $response, $exception);
        }

        // Send the response
        $response->send();
    }
1147171
protected static function commonError(Response $response, \Exception $ex): Response
    {
        $data = [
            "message" => "Somethings are wrong",
            "status" => "error"
        ];

        if (cfg::htrFileConfigs()->devmode ?? false) {
            $data['dev_error'] = $ex->getMessage();
        }
        return $response->withJson($data, 500);
    }
42033
public static function exceptionToResponse(\Throwable $exception): ResponseInterface
    {
        self::$reserved = null;

        if ($exception instanceof HttpErrorException) {
            $statusCode = $exception->getCode();
        } else {
            $userAgent = self::$request->getHeaderLine('User-Agent');
            $statusCode = $userAgent && \strpos($userAgent, 'MSIE ') !== false ? 503 : 500;
        }

        $headers = [];
        $template = 'html';
        $isHtmlMode = false;

        $accept = self::$request->getHeaderLine('Accept');
        foreach (static::$handlers as $template => $types) {
            foreach ($types as $type) {
                if (\stripos($accept, $type) !== false) {
                    $headers['Content-Type'] = $type;
                    break 2;
                }
            }
        }

        if ($headers === []) {
            $isHtmlMode = Helpers::isHtmlMode();

            if ($isHtmlMode) {
                $template = '500';
                $headers['Content-Type'] = 'text/html; charset=UTF-8';
            }
        }

        Helpers::improveException($exception);
        self::removeOutputBuffers(true);

        if (self::isProductionMode()) {
            try {
                self::log($exception, self::getExceptionLevel($exception));
            } catch (\Throwable $e) {
            }

            $body = self::exceptionTemplate($template, $exception, empty($e));
        } elseif ($isHtmlMode || Helpers::isAjax()) {
            $body = self::getBlueScreen()->render($exception);
        } else {
            $level = self::getExceptionLevel($exception);
            self::chromeLog($exception, $level);

            $s = Helpers::getClass($exception) . ($exception->getMessage() === '' ? '' : ': ' . $exception->getMessage())
                . ' in ' . $exception->getFile() . ':' . $exception->getLine()
                . "\nStack trace:\n" . $exception->getTraceAsString();
            try {
                $file = self::log($exception, $level);
                if ($file) {
                    $headers['X-Tracy-Error-Log'] = $file;
                }

                $body = "$s\n" . ($file ? "(stored in $file)\n" : '');
            } catch (\Throwable $e) {
                $body = "$s\nUnable to log error: {$e->getMessage()}\n";
            }
        }

        return self::writeToResponse(
            Factory::response($statusCode, $body, $headers)
        );
    }
531609
public static function factory(RequestInterface $request, Response $response)
    {
        if ($response->isClientError()) {
            $label = 'Client error response';
            $class = __NAMESPACE__ . '\\ClientErrorResponseException';
        } elseif ($response->isServerError()) {
            $label = 'Server error response';
            $class = __NAMESPACE__ . '\\ServerErrorResponseException';
        } else {
            $label = 'Unsuccessful response';
            $class = __CLASS__;
        }

        $message = $label . PHP_EOL . implode(PHP_EOL, array(
            '[status code] ' . $response->getStatusCode(),
            '[reason phrase] ' . $response->getReasonPhrase(),
            '[url] ' . $request->getUrl(),
        ));

        $e = new $class($message);
        $e->setResponse($response);
        $e->setRequest($request);

        return $e;
    }