@param RequestInterface  $request
@param ResponseInterface $response
@param \Exception|null   $previous

@return AcmeCoreServerException
962533
public function createAcmeExceptionForResponse(
        RequestInterface $request,
        ResponseInterface $response,
        \Exception $previous = null
    ) {
        $body = \GuzzleHttp\Psr7\copy_to_string($response->getBody());

        try {
            $data = JsonDecoder::decode($body, true);
        } catch (\InvalidArgumentException $e) {
            $data = null;
        }

        if (!$data || !isset($data['type'], $data['detail'])) {
            // Not JSON: not an ACME error response
            return $this->createDefaultExceptionForResponse($request, $response, $previous);
        }

        $type = preg_replace('/^urn:(ietf:params:)?acme:error:/i', '', $data['type']);

        if (!isset(self::$exceptions[$type])) {
            // Unknown type: not an ACME error response
            return $this->createDefaultExceptionForResponse($request, $response, $previous);
        }

        $exceptionClass = self::$exceptions[$type];

        return new $exceptionClass(
            $request,
            sprintf('%s (on request "%s %s")', $data['detail'], $request->getMethod(), $request->getUri()),
            $previous
        );
    }
1267442
public function add(RequestInterface $request, Response $response = null)
    {
        if (!$response && $request->getResponse()) {
            $response = $request->getResponse();
        }

        $this->transactions[] = array('request' => $request, 'response' => $response);
        if (count($this->transactions) > $this->getlimit()) {
            array_shift($this->transactions);
        }

        return $this;
    }
441420
public function runBefore(Request $request, Response $response)
    {
        foreach ($this->middlewares as $middleware) {
            if (class_exists($middleware)) {
                $instance = new $middleware($request, $response);
                if ($instance instanceof MiddlewareAbstract) {
                    /* @var $instance MiddlewareAbstract */
                    $instance->onBefore();
                    $this->running[] = $instance;
                }
            }
        }
    }
293476
private function onBefore(RequestInterface $request)
    {
        $headers = $this->createHeaders($request);
        foreach ($headers as $headerKey => $headerValue) {
            $request = $request->withHeader($headerKey, $headerValue);
        }

        return $request;
    }
113554
public function route(RequestInterface $request, ResponseInterface $response, Context $context = null)
    {
        $this->level++;

        $this->eventDispatcher->dispatch(Event::REQUEST_INCOMING, new RequestIncomingEvent($request));

        // load controller
        if ($context === null) {
            $factory = $this->config->get('psx_context_factory');
            if ($factory instanceof \Closure) {
                $context = $factory();
            } else {
                $context = new Context();
            }
        }

        try {
            $this->loader->load($request, $response, $context);
        } catch (StatusCode\NotModifiedException $e) {
            $response->setStatus($e->getStatusCode());
            $response->setBody(new StringStream());
        } catch (StatusCode\RedirectionException $e) {
            $response->setStatus($e->getStatusCode());
            $response->setHeader('Location', $e->getLocation());
            $response->setBody(new StringStream());
        } catch (\Throwable $e) {
            $this->eventDispatcher->dispatch(Event::EXCEPTION_THROWN, new ExceptionThrownEvent($e, new ControllerContext($request, $response)));

            $this->handleException($e, $response);

            try {
                $context->setException($e);

                $class      = isset($this->config['psx_error_controller']) ? $this->config['psx_error_controller'] : ErrorController::class;
                $controller = $this->controllerFactory->getController($class, $context);

                $this->loader->execute($controller, $request, $response);
            } catch (\Throwable $e) {
                // in this case the error controller has thrown an exception.
                // This can happen i.e. if we can not represent the error in an
                // fitting media type. In this case we send json to the client

                $this->handleException($e, $response);

                $record = $this->exceptionConverter->convert($e);

                $response->setHeader('Content-Type', 'application/json');
                $response->setBody(new StringStream(Parser::encode($record, JSON_PRETTY_PRINT)));
            }
        }

        // for HEAD requests we never return a response body
        if ($request->getMethod() == 'HEAD') {
            $response->setHeader('Content-Length', $response->getBody()->getSize());
            $response->setBody(new StringStream(''));
        }

        $this->eventDispatcher->dispatch(Event::RESPONSE_SEND, new ResponseSendEvent($response));

        $this->level--;

        return $response;
    }
591557
private function setOriginalSoapExceptionContent(\Exception $previous = null)
    {
        if (is_object($previous) && $previous instanceof \SoapFault) {
            $this->originalMessage = $previous->faultstring;
            $this->originalCode = $previous->faultcode;
        }

        return $this;
    }
1344252
public function dispatch(Request $request, Response $response, $next = null)
    {
        $controller = $this->currentController;

        $controller->setRequest($request)->setResponse($response);

        $this->prepareExecute();

        // @event: onPackageBeforeExecute
        $this->getDispatcher()->triggerEvent('onPackageBeforeExecute', [
            'package' => $this,
            'controller' => &$controller,
            'task' => $controller,
        ]);

        $result = $controller->execute();

        $result = $this->postExecute($result);

        // @event: onPackageAfterExecute
        $this->getDispatcher()->triggerEvent('onPackageAfterExecute', [
            'package' => $this,
            'controller' => $controller,
            'result' => &$result
        ]);

        $response = $controller->getResponse();

        if ($result !== null) {
            // Render view if return value is a view object,
            // don't use (string) keyword to make sure we can get Exception when error occurred.
            // @see  https://bugs.php.net/bug.php?id=53648
            if ($result instanceof AbstractView) {
                $result = $result->render();
            } elseif (is_stringable($result)) {
                $result = (string) $result;
            } elseif (is_array($result) || is_object($result)) {
                $result = json_encode($result);
            }

            $response->getBody()->write((string) $result);
        }

        return $response;
    }
1319142
public static function create(
      RequestInterface $request,
      ResponseInterface $response = null,
      \Exception $previous = null,
      array $ctx = []
    ) {
        $e = parent::create($request, $response, $previous);
        if ($response === null) {
            return $e;
        }

        // Re-create the exception to alter the message.
        $details = self::getErrorDetails($response);
        if (!empty($details)) {
            $className = get_class($e);
            $e = new $className($e->getMessage() . $details, $e->getRequest(), $e->getResponse());
        }

        return $e;
    }
574112
protected function handleRequestException(Request $request, RequestException $previousException)
    {
        if (null !== $previousException) {
            $response = $previousException->getResponse();

            if (null == $response || ($response->getStatusCode() >= 500 && $response->getStatusCode() <= 599)) {
                throw new NullResponseException($this->request, $previousException);
            }
        }

        throw $this->createApiException(
            $request,
            $this->createResponse($previousException->getResponse()),
            $previousException
        );
    }
1247287
public function execute(ServerRequestInterface $request, ResponseInterface $response)
    {
        try {
            return $this->router->start($request, $response);
        } catch (\Exception $e) {
            $this->logger->warning('Unexpected exception: ' . $e->getMessage());
            $this->logger->debug($e->__toString());

            return $response->withStatus(500)
                ->withBody(new StringStream($e->getMessage()));
        }
    }
1267870
private function getHttpResponse(RequestInterface $request): ?ResponseInterface
    {
        try {
            return $this->httpClient->send($request);
        } catch (TooManyRedirectsException $tooManyRedirectsException) {
            return $this->httpHistoryContainer->getLastResponse();
        } catch (BadResponseException $badResponseException) {
            $this->badRequestCount++;

            if ($this->isBadRequestLimitReached()) {
                return $badResponseException->getResponse();
            }

            return $this->getHttpResponse($request);
        } catch (HttpConnectException $connectException) {
            throw $connectException;
        } catch (RequestException $requestException) {
            if ($this->isCurlException($requestException)) {
                throw new HttpConnectException(
                    $requestException->getMessage(),
                    $requestException->getRequest(),
                    $requestException->getPrevious()
                );
            }

            $this->badRequestCount++;

            if ($this->isBadRequestLimitReached()) {
                return $requestException->getResponse();
            }

            return $this->getHttpResponse($request);
        }
    }
486849
public static function create(
        RequestInterface $request,
        ResponseInterface $response = null,
        \Exception $previous = null
    ) {
        if (!$response) {
            return new self('Error completing request', $request, null, $previous);
        }

        $level = $response->getStatusCode()[0];
        if ($level == '4') {
            $label = 'Client error response';
            $className = __NAMESPACE__ . '\\ClientException';
        } elseif ($level == '5') {
            $label = 'Server error response';
            $className = __NAMESPACE__ . '\\ServerException';
        } else {
            $label = 'Unsuccessful response';
            $className = __CLASS__;
        }

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

        return new $className($message, $request, $response, $previous);
    }
755766
public function httpGet(RequestInterface $request, ResponseInterface $response)
    {
        $queryParams = $request->getQueryParameters();
        if (!array_key_exists('mount', $queryParams)) {
            return;
        }

        $currentUri = $request->getAbsoluteUrl();

        // Stripping off everything after the ?
        list($currentUri) = explode('?', $currentUri);

        $this->davMount($response, $currentUri);

        // Returning false to break the event chain
        return false;
    }
609061
public function process(Request $request, DelegateInterface $frame)
    {
        try {
            // Try returning the response normally
            return $frame->next($request);
        } catch (OAuthServerException $e) {
            // Generate an error based on the exception
            return $e->generateHttpResponse(new Response());
        }
    }
380373
protected function beforeDispatch(RequestInterface $request, ResponseInterface $response)
    {
        RequestContext::setRequest($request);
        RequestContext::setResponse($response);

        // Trigger 'Before Request' event
        App::trigger(HttpServerEvent::BEFORE_REQUEST);
    }
875569
public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        if (false === $this->enabled) {
            return;
        }

        $profile = new Profile(substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6));
        $profile->setTime(time());
        $profile->setUrl($request->getUri());
        $profile->setMethod($request->getMethod());
        $profile->setStatusCode($response->getStatusCode());
        try {
            $profile->setIp($request->getClientIp());
        } catch (ConflictingHeadersException $e) {
            $profile->setIp('Unknown');
        }

        if ($prevToken = $response->headers->get('X-Debug-Token')) {
            $response->headers->set('X-Previous-Debug-Token', $prevToken);
        }

        $response->headers->set('X-Debug-Token', $profile->getToken());

        foreach ($this->collectors as $collector) {
            $collector->collect($request, $response, $exception);

            // we need to clone for sub-requests
            $profile->addCollector(clone $collector);
        }

        return $profile;
    }
867523
public static function invalidRequest($parameter, $hint = null, Throwable $previous = null)
    {
        $errorMessage = 'The request is missing a required parameter, includes an invalid parameter value, ' .
            'includes a parameter more than once, or is otherwise malformed.';
        $hint = ($hint === null) ? sprintf('Check the `%s` parameter', $parameter) : $hint;

        return new static($errorMessage, 3, 'invalid_request', 400, $hint, null, $previous);
    }