@inheritdoc

This code provides an ability to transform various exceptions in API (application specific,
authorization, 3rd party, etc) and convert it to JSON API error.
763676
public static function convert(Throwable $throwable): ?JsonApiException
    {
        $converted = null;

        if ($throwable instanceof AuthorizationException) {
            $httpCode  = 403;
            $action    = $throwable->getAction();
            $errors    = (new ErrorCollection())
                ->addDataError(
                    'Unauthorized',
                    "You are not unauthorized for action `$action`.",
                    null,
                    null,
                    null,
                    $httpCode
                );
            $converted = new JsonApiException($errors, $httpCode, $throwable);
        } elseif ($throwable instanceof AuthenticationException) {
            $httpCode  = 401;
            $errors    = (new ErrorCollection())
                ->addDataError(
                    'Authentication failed',
                    'Authentication failed',
                    null,
                    null,
                    null,
                    $httpCode
                );
            $converted = new JsonApiException($errors, $httpCode, $throwable);
        }

        return $converted;
    }
962800
public static function fromJson($json){
    if(is_string($json)){
      $json = json_decode($json);
    }

    if (!isset($json->error) || is_null($json->error) ) {
      return new self($json->uuid, new DateTime($json->timestamp), $json->status);
    } else {
      if(!property_exists($json->error, 'code')){
        throw new BadResponseException('Required parameter "error.code" not found');
    }
      throw AbstractReport::errorToException($json->error->code);
    }
  }
246543
private function checkForCurlErrors($json)
    {
        if ($json && isset($json->errors)) {
            // Get errors
            $errors = implode(', ', array_map(function ($error) {
                return $error->message;
            }, $json->errors));

            // fetch sync key for event handling
            if (isset($json->sync)) {
                $this->syncKey = $json->sync;
            }

            throw new Exception($errors, $this->http_code);
        }
    }
286185
private function convertToGoogleException($ex)
    {
        switch ($ex->getCode()) {
            case Code::INVALID_ARGUMENT:
                $exception = Exception\BadRequestException::class;
                break;

            case Code::NOT_FOUND:
            case Code::UNIMPLEMENTED:
                $exception = Exception\NotFoundException::class;
                break;

            case Code::ALREADY_EXISTS:
                $exception = Exception\ConflictException::class;
                break;

            case Code::FAILED_PRECONDITION:
                $exception = Exception\FailedPreconditionException::class;
                break;

            case Code::UNKNOWN:
                $exception = Exception\ServerException::class;
                break;

            case Code::INTERNAL:
                $exception = Exception\ServerException::class;
                break;

            case Code::ABORTED:
                $exception = Exception\AbortedException::class;
                break;

            case Code::DEADLINE_EXCEEDED:
                $exception = Exception\DeadlineExceededException::class;
                break;

            default:
                $exception = Exception\ServiceException::class;
                break;
        }

        $metadata = [];
        if ($ex->getMetadata()) {
            foreach ($ex->getMetadata() as $type => $binaryValue) {
                if (!isset($this->metadataTypes[$type])) {
                    continue;
                }
                $metadataElement = new $this->metadataTypes[$type];
                $metadataElement->mergeFromString($binaryValue[0]);
                $metadata[] = $this->serializer->encodeMessage($metadataElement);
            }
        }

        return new $exception($ex->getMessage(), $ex->getCode(), $ex, $metadata);
    }
156310
protected function transformException(Exception $exception)
    {
        if (Request::capture()->wantsJson()) {
            $this->transformAuthException($exception);
            $this->transformEloquentException($exception);
            $this->transformValidationException($exception);
        }
    }
514101
public function jsonArray()
    {

        if (!$this->isContentType('application/json')) {
            throw new Exception('Response is not JSON');
        }

        if (empty($this->_jsonAsArray)) {
            $this->_jsonAsArray = Utils::json_parse($this->text(), true);
        }

        return $this->_jsonAsArray;

    }
1207102
protected function jsonErrorException($code)
    {
        $this->defineCodesErrorJson();
        
        switch($code)
        {
            case JSON_ERROR_DEPTH:
                throw new LengthException('The maximum stack depth has been exceeded');
                break;
            case JSON_ERROR_STATE_MISMATCH:
                throw new UnexpectedValueException('Invalid or malformed JSON');
                break;
            case JSON_ERROR_CTRL_CHAR:
                throw new UnexpectedValueException('Control character error, possibly incorrectly encoded');
                break;
            case JSON_ERROR_SYNTAX:
                throw new RuntimeException('Syntax error');
                break;
            case JSON_ERROR_UTF8:
                throw new RuntimeException('Malformed UTF-8 characters, possibly incorrectly encoded');
                break;
            case JSON_ERROR_RECURSION:
                throw new RuntimeException('One or more recursive references in the value to be encoded');
                break;
            case JSON_ERROR_INF_OR_NAN:
                throw new RuntimeException('One or more NAN or INF values in the value to be encoded');
                break;
            case JSON_ERROR_UNSUPPORTED_TYPE:
                throw new UnexpectedValueException('A value of a type that cannot be encoded was given');
                break;
            default :
                $msg = (function_exists('json_last_error_msg')) ? json_last_error_msg() : 'Code ERROR not valid for JSON';
                throw new UnexpectedValueException($msg);
        }
    }
267692
protected function _actionException($context)
    {
        $exception = $context->data;

        //if AnException then conver it to AnException
        if ($exception instanceof AnException) {
            $exception = new RuntimeException($exception->getMessage(), $exception->getCode());
        }

        //if cli just print the error and exit
        if (PHP_SAPI == 'cli') {
            print "\n";
            print $exception."\n";
            print debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
            exit(0);
        }

        $code = $exception->getCode();

        //check if the error is code is valid
        if ($code < 400 || $code >= 600) {
            $code = AnHttpResponse::INTERNAL_SERVER_ERROR;
        }

        $context->response->status = $code;

        $config = array(
            'response' => $context->response,
            'request' => $context->request,
            'theme' => $this->_application->getTemplate()
        );

        //if ajax or the format is not html
        //then return the exception in json format
        if ($context->request->isAjax() || $context->request->getFormat() != 'html') {
            $context->request->setFormat('json');
        }

        $this->getService('com:application.controller.exception', $config)
        ->layout('error')
        ->render($exception);

        $this->send($context);
    }
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);
    }
308892
def translate_exception(exc, kwargs):
    
    error = exc.response['Error']
    error.setdefault('Message', '')
    err_class = EXC.get(error['Code'], DynamoDBError)
    return err_class(exc.response['ResponseMetadata']['HTTPStatusCode'],
                     exc_info=sys.exc_info(), args=pformat(kwargs), **error)
513988
private function handleApiError(
        $response_body,
        $response_code,
        $response_headers,
        $json_resp
    ) {

        switch ($response_code) {
            case 400:
                // format for the errors:
                // - [{"field":"amount","message":"Can refund at most GBP 0"}]
                // - [{"code":2,"text":"Invalid card details", "client": true, "merchant": false}]
                $message = "Bad (invalid) request";
                // @TODO - extract error parsing logic
                if ($json_resp && is_array($json_resp) && ! empty($json_resp)) {
                    if (isset($json_resp[0]['message'])) {
                        $message = $json_resp[0]['message'];
                    } else if (isset($json_resp[0]['text'])) {
                        $message = $json_resp[0]['text'];
                    }
                }
                throw new InvalidRequest($message,
                    $response_code, $response_body, $json_resp,
                    $response_headers);
            case 401:
                throw new Unauthorized("You need to provide credentials (an app's API key).",
                    $response_code,
                    $response_body, $json_resp,
                    $response_headers);
            case 403:
                throw new Forbidden("You are correctly authenticated but do not have access.",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            case 404:
                throw new NotFound("Resource not found.",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            case 409:
                throw new Conflict("Everything you submitted was fine at the time of validation, but something changed in the meantime and came into conflict with this (e.g. double-capture).",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            default:
                throw new ApiException("Unknown api error",
                    $response_code,
                    $response_body,
                    $json_resp,
                    $response_headers);
        }
    }
1138661
public static function fromJson($json){
    if(is_string($json)){
      $json = json_decode($json);
    }

    if(!property_exists($json, 'error')){
      throw new BadResponseException('Required parameter "error" not found');
    }
    
    if(is_null($json->error)){
      $shortReport = ShortReport::fromJson($json);

      if(!property_exists($json, 'payload')){
        throw new BadResponseException('Required parameter "payload" not found');
      }
      if(!property_exists($json, 'group_code')){
        throw new BadResponseException('Required parameter "group_code" not found');
      }
      if(!property_exists($json, 'daemon_code')){
        throw new BadResponseException('Required parameter "daemon_code" not found');
      }
      if(!property_exists($json, 'device_code')){
        throw new BadResponseException('Required parameter "device_code" not found');
      }
      if(!property_exists($json, 'callback_url')){
        throw new BadResponseException('Required parameter "callback_url" not found');
      }

      $payload = Payload::fromJson($json->payload);
      return new self(
        $shortReport->getUuid(),
        $shortReport->getTimestamp(),
        $shortReport->getStatus(),
        $payload,
        $json->group_code,
        $json->daemon_code,
        $json->device_code,
        $json->callback_url
      );
    }
    else{
      if(!property_exists($json->error, 'code')){
        throw new BadResponseException('Required parameter "error.code" not found');
      }

      throw AbstractReport::errorToException((int) $json->error->code);
    }
  }
1339773
def handle_api_exception(error):
    
    _mp_track(
        type="exception",
        status_code=error.status_code,
        message=error.message,
    )

    response = jsonify(dict(
        message=error.message
    ))
    response.status_code = error.status_code
    return response
535521
public function transform(Exception $exception)
    {
        if ($exception instanceof AuthorizationException) {
            $exception = new AccessDeniedHttpException($exception->getMessage(), $exception, $exception->getCode());
        }

        return $exception;
    }
772740
private function convertException(Exception $e)
    {
        $data = [];
        $data['message']  = $e->getMessage();
        $data['code']     = $e->getCode();
        $data['trace']    = $this->filterTrace($e->getTrace());
        $data['status']   = Response::HTTP_INTERNAL_SERVER_ERROR;

        // determine the relevant file
        $firstTraceEntry = !empty($data['trace']) ? reset($data['trace']) : null;
        if ($firstTraceEntry !== null && isset($firstTraceEntry['file']) && isset($firstTraceEntry['line'])) {
            $data['file'] = $firstTraceEntry['file'];
            $data['line'] = $firstTraceEntry['line'];
        }
        else {
            $data['file'] = $e->getFile();
            $data['line'] = $e->getLine();
        }

        if ($e instanceof HttpException) {
            $data['status'] = $e->getStatusCode() ?: Response::HTTP_INTERNAL_SERVER_ERROR;
        }
        else if ($e instanceof QueryException) {
            $data['ansiCode']   = isset($e->errorInfo[0]) ? $e->errorInfo[0] : null;
            $data['driverCode'] = isset($e->errorInfo[1]) ? $e->errorInfo[1] : null;
            if (!empty($e->errorInfo[2])) {
                $data['message'] = $e->errorInfo[2];
            }
            $data['sql'] = $e->getDump();
        }

        return $data;
    }
268095
protected function createJsonApiResponse(JsonApiException $exception)
    {
        /** @var ResponsesInterface $responses */
        $responses = $this->container->make(ResponsesInterface::class);

        $errors = $exception->getErrors();
        $code   = $exception->getHttpCode();

        switch (count($errors)) {
            case 0:
                $response = $responses->getCodeResponse($code);
                break;

            case 1:
                $response = $responses->getErrorResponse($errors[0], $code);
                break;

            default:
                $response = $responses->getErrorResponse($errors, $code);
                break;
        }

        return $response;
    }
768
private function createInternalServerError(\Exception $exception)
    {
        $message = sprintf(
            '%s: %s (uncaught exception) at %s line %s',
            get_class($exception),
            $exception->getMessage(),
            $exception->getFile(),
            $exception->getLine()
        );

        $this->logger->error($message, array('exception' => $exception));

        $response = [
            'status'  => 'ERROR',
            'message' => JsonResponse::$statusTexts[JsonResponse::HTTP_INTERNAL_SERVER_ERROR]
        ];

        if ($this->debug) {
            $response['exception'] = $this->formatException($exception);
        }

        return new JsonResponse($response, JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
    }