Handle a failed response by creating a specific exception for the given
response.

@param Response $response
@param DriverExceptionInterface $exception
@return DriverException
550450
public function createDbalException(Response $response, DriverExceptionInterface $exception) {
        switch ($response->getStatusCode()) {
            case Response::HTTP_BAD_REQUEST:
                return new DBALException\SyntaxErrorException($response->getContent(), $exception);

            case Response::HTTP_METHOD_NOT_ALLOWED:
            case Response::HTTP_NOT_ACCEPTABLE:
            case Response::HTTP_REQUEST_TIMEOUT:
            case Response::HTTP_LENGTH_REQUIRED:
            case Response::HTTP_INTERNAL_SERVER_ERROR:
                return new DBALException\ServerException($response->getContent(), $exception);
            
            case Response::HTTP_CONFLICT:
                return new DBALException\ConstraintViolationException($response->getContent(), $exception);

            case Response::HTTP_UNAUTHORIZED:
            case Response::HTTP_FORBIDDEN:
            case Response::HTTP_PROXY_AUTHENTICATION_REQUIRED:
            case Response::HTTP_BAD_GATEWAY:
            case Response::HTTP_SERVICE_UNAVAILABLE:
            case Response::HTTP_GATEWAY_TIMEOUT:
                return new DBALException\ConnectionException($response->getContent(), $exception);

            default:
                return new DBALException\DriverException($response->getContent(), $exception);
        }
    }
9878
protected function handleNotJsonException(ResponseInterface $response)
    {
        if (true !== $response->hasHeader('Content-Type')
            || 'application/json' !== $response->getHeaderLine('Content-Type')
        ) {
            throw new ApiException(
                \sprintf(
                    'Waiting for json response but %s given',
                    $response->getHeaderLine('Content-Type')
                ),
                $this->getRequest(),
                $response
            );
        }
    }
855300
private function parseExceptionForErrorMessages(Exception $exception)
    {
        if (! $exception instanceof BadResponseException) {
            return new ApiException($exception->getMessage(), 0, $exception);
        }

        $response = $exception->getResponse();

        if (null === $response) {
            return new ApiException('Response is NULL.', 0, $exception);
        }

        Psr7\rewind_body($response);
        $responseBody = $response->getBody()->getContents();
        $decodedResponseBody = json_decode($responseBody, true);

        if (null !== $decodedResponseBody && isset($decodedResponseBody['error']['message']['value'])) {
            $errorMessage = $decodedResponseBody['error']['message']['value'];
        } else {
            $errorMessage = $responseBody;
        }

        $this->checkWhetherRateLimitHasBeenReached($response, $errorMessage);

        return new ApiException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode(), $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;
    }
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)
        );
    }
1212420
public static function handleError(BadResponseException $exception)
    {
        $response_body = (string) $exception->getResponse()->getBody();
        $array_body = decode($response_body);

        $code = $exception->getResponse()->getStatusCode();

        $lookForKeys = ['message', 'code', 'error'];

        foreach ($lookForKeys as $key) {
            if (isset($array_body[$key])) {
                $message = $array_body[$key];
            }
        }

        if (!$message) {
            $message = 'unknown_error';
        }

        throw new JSONError($message, $code, $array_body);
    }
190849
public function handleException(\Exception $exception) {
    // get error level
    $logFunction = 'error';
    if ($exception instanceof ApplicationException) {
      $logFunction = $exception->getError()->getLevel() == ApplicationError::LEVEL_WARNING ?
              'warn' : 'error';
    }
    self::$logger->$logFunction($exception);

    try {
      if (ObjectFactory::getInstance('configuration') != null) {
        // rollback current transaction
        $persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
        $persistenceFacade->getTransaction()->rollback();

        // redirect to failure action
        if ($this->request) {
          $error = ApplicationError::fromException($exception);
          $this->request->addError($error);
          $this->response->addError($error);
          $this->request->setAction('failure');
          $this->response->setAction('failure');
          $this->response->setStatus($error->getStatusCode());
          ObjectFactory::getInstance('actionMapper')->processAction($this->request, $this->response);
          return;
        }
      }
      throw $exception;
    }
    catch (\Exception $ex) {
      self::$logger->error($ex->getMessage()."\n".$ex->getTraceAsString());
    }
  }
791848
public function translateResponseToException(\Amp\Artax\Response $response) {
        $status = $response->getStatus();
        if ($status < 200 || $status >= 300) {
            return new BadResponseException(
                "Status $status is not treated as OK.",
                $response
            );
        }

        return null;
    }
85893
final protected function createApiException(ResponseInterface $response, $data, $code = null, $message = null)
    {
        $e = new ApiException(get_class($this).' #'.$code.': '.$message);
        $e->setResponse($response);
        $e->setData($data);
        $e->setErrorCode($code);
        $e->setErrorMessage($message);

        return $e;
    }
238459
private function handleUncaughtException(\Throwable $exception, Request $request) : Response
    {
        $httpException = new HttpInternalServerErrorException('Uncaught exception', $exception);

        return $this->handleHttpException($httpException, $request);
    }
901994
protected function failJob($job, Exception $exception)
    {
        if ($job instanceof JobInterface) {
            $payload = $job->getPayload();
            $queue   = $job->getQueue();
        } else {
            $payload = $job;
            $queue   = isset($job['queue']) ? $job['queue'] : null;
        }

        $id = isset($job['id']) ? $job['id'] : null;

        if ($id) {
            try {
                $status = $this->resque->getStatusFactory()->forId($id);
                $status->update(Status::STATUS_FAILED);
            } catch (JobIdException $e) {
                $this->logger->warning($e);
            }
        } // else no status to update

        $this->resque->getFailureBackend()->receiveFailure(
            $payload,
            $exception,
            $this,
            $queue
        );

        $this->getResque()->getStatistic('failed')->incr();
        $this->getStatistic('failed')->incr();
    }
440077
private function throwFromErrorResponse(HttpResponse $response, array $body)
    {
        list($message, $code, $extra) = $this->getErrorStringFromResponseBody($body);

        $exceptions = [
            400 => BadRequest::class,
            401 => Unauthorized::class,
            403 => Forbidden::class,
            404 => NotFound::class,
            406 => NotAcceptable::class,
            410 => Gone::class,
            420 => RateLimitTriggered::class,
            422 => UnprocessableEntity::class,
            429 => RateLimitTriggered::class,
            500 => ServerError::class,
            502 => BadGateway::class,
            503 => ServiceUnavailable::class,
            504 => GatewayTimeout::class,
        ];

        if (!array_key_exists($response->getStatus(), $exceptions)) {
            return;
        }

        throw new $exceptions[$response->getStatus()]($message, $code, null, $extra);
    }
310287
private function mapException(ControllerException $exception): ClientException
    {
        switch ($exception->getCode()) {
            case ControllerException::BAD_ACTION:
                //no break
            case ControllerException::NOT_FOUND:
                return new NotFoundException($exception->getMessage());
            case ControllerException::FORBIDDEN:
                return new ForbiddenException($exception->getMessage());
            default:
                return new BadRequestException($exception->getMessage());
        }
    }
732698
public function responseProcessor($response, $format, $curlError)
    {
        $format = (is_null($format)) ? $this->config->getFormat() : $format;
        switch ($format) {
            case 'json':
                return $response;
            case 'object':
                if ('NO_CURL_ERROR' == current($curlError)) {
                    return json_decode($response);
                } else {
                    $responseError = new \stdClass();
                    $responseError->error = $curlError;
                    return $responseError;
                }
                break;
            default:
                throw new BadParametersException(
                    sprintf('the "%s" format is not supported.', $format)
                );
        }
    }
65577
protected function handleError($response) {
    $errorMsg = $response->getValue('errorMsg');
    self::$logger->error("Error in remote call to ".$this->serverCli.": ".$errorMsg."\n".$response->toString());
    throw new \RuntimeException("Error in remote call to ".$this->serverCli.": ".$errorMsg);
  }
996545
public static function clientException(ResponseInterface $response, $data)
    {
        return static::fromResponse(
            $response,
            isset($data['message']) ? $data['message'] : $response->getReasonPhrase()
        );
    }
497377
protected function parseResponse(ResponseInterface $response)
    {
        $response = json_decode($response->getBody()->getContents());

        if (isset($response->success) && $response->success) {
            return $response->data;
        }

        throw new \Exception($response->error_info, $response->error_code);
    }