Mimics the exception handling logic in ``client._get_body``, but
    for geolocation which uses a different response format.
551260
def _geolocation_extract(response):
    
    body = response.json()
    if response.status_code in (200, 404):
        return body

    try:
        error = body["error"]["errors"][0]["reason"]
    except KeyError:
        error = None

    if response.status_code == 403:
        raise exceptions._OverQueryLimit(response.status_code, error)
    else:
        raise exceptions.ApiError(response.status_code, error)
405724
function(body) {
    if (_.isString(body)) {
      return body;
    } else if (_.isObject(body) && _.isString(body.error)) {
      return body.error;
    } else if (_.isObject(body) && _.isString(body.msg)) {
      return body.msg;
    } else if (_.isObject(body) && _.isObject(body.error)) {
      return this._extractError(body.error);
    } else if (_.isObject(body) && _.isString(body.message)) {
      return body.message;
    } else if (_.isObject(body) &&
      body.meta &&
      _.isString(body.meta.error_message)) {
      return body.meta.error_message;
    } else {
      return 'Unknown Request Error';
    }
  }
578441
function (err, body) {
          if (!err) {
            var val = body.GET
            if (val) {
              /*
              {
                "GET": "[resource]@[id]"
              }
              */
              val = val.split('@')
              // overwrite body
              body = {
                'resource': val[0],
                '_id': val[1]
              }

              // success, pass the object
              callback(null, body)
            } else {
              // Redis key not found
              body = {
                'status': 404,
                'error_code': -44,
                'message': 'Page not found, invalid slug or store ID'
              }
              var msg = body.message
              errorHandling(callback, msg, body)
            }
          } else {
            // just pass the error
            callback(err, body)
          }
        }
493540
def extract_roads_body(response)
        begin
          body = MultiJson.load(response.body, :symbolize_keys => true)
        rescue
          unless response.status_code == 200
            check_response_status_code(response)
          end
          raise GoogleMapsService::Error::ApiError.new(response), 'Received a malformed response.'
        end

        check_roads_body_error(response, body)

        unless response.status_code == 200
          raise GoogleMapsService::Error::ApiError.new(response)
        end
        return body
      end
237814
def _map_exception(e):
    """"""
    if isinstance(e, urllib3.exceptions.MaxRetryError):
        if not e.reason:
            return e
        e = e.reason
    message = e.args[0] if e.args else ''
    if isinstance(e, urllib3.exceptions.ResponseError):
        if 'too many redirects' in message:
            return httplib2.RedirectLimit(message)
    if isinstance(e, urllib3.exceptions.NewConnectionError):
        if ('Name or service not known' in message or
                'nodename nor servname provided, or not known' in message):
            return httplib2.ServerNotFoundError(
                'Unable to find hostname.')
        if 'Connection refused' in message:
            return socket.error((errno.ECONNREFUSED, 'Connection refused'))
    if isinstance(e, urllib3.exceptions.DecodeError):
        return httplib2.FailedToDecompressContent(
            'Content purported as compressed but not uncompressable.',
            httplib2.Response({'status': 500}), '')
    if isinstance(e, urllib3.exceptions.TimeoutError):
        return socket.timeout('timed out')
    if isinstance(e, urllib3.exceptions.SSLError):
        return ssl.SSLError(*e.args)

    return e
1257817
def exception_handle(method):
    """"""

    def wrapper(*args, **kwargs):
        try:
            result = method(*args, **kwargs)
            return result
        except ProxyError:
            LOG.exception('ProxyError when try to get %s.', args)
            raise ProxyError('A proxy error occurred.')
        except ConnectionException:
            LOG.exception('ConnectionError when try to get %s.', args)
            raise ConnectionException('DNS failure, refused connection, etc.')
        except Timeout:
            LOG.exception('Timeout when try to get %s', args)
            raise Timeout('The request timed out.')
        except RequestException:
            LOG.exception('RequestException when try to get %s.', args)
            raise RequestException('Please check out your network.')

    return wrapper
867664
def handle_exception(error):
    """"""
    try:
        if _get_acceptable_response_type() == JSON:
            response = jsonify(error.to_dict())
            response.status_code = error.code
            return response
        else:
            return error.abort()
    except InvalidAPIUsage:
        # In addition to the original exception, we don't support the content
        # type in the request's 'Accept' header, which is a more important
        # error, so return that instead of what was originally raised.
        response = jsonify(error.to_dict())
        response.status_code = 415
        return response
441377
def handle_api_exceptions(
    ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False
):
    """"""
    # flake8: ignore=C901
    # Use stderr for messages if the output is something else (e.g.  # JSON)
    use_stderr = opts.output != "pretty"

    try:
        yield
    except ApiException as exc:
        if nl:
            click.echo(err=use_stderr)
            click.secho("ERROR: ", fg="red", nl=False, err=use_stderr)
        else:
            click.secho("ERROR", fg="red", err=use_stderr)

        context_msg = context_msg or "Failed to perform operation!"
        click.secho(
            "%(context)s (status: %(code)s - %(code_text)s)"
            % {
                "context": context_msg,
                "code": exc.status,
                "code_text": exc.status_description,
            },
            fg="red",
            err=use_stderr,
        )

        detail, fields = get_details(exc)
        if detail or fields:
            click.echo(err=use_stderr)

            if detail:
                click.secho(
                    "Detail: %(detail)s"
                    % {"detail": click.style(detail, fg="red", bold=False)},
                    bold=True,
                    err=use_stderr,
                )

            if fields:
                for k, v in six.iteritems(fields):
                    field = "%s Field" % k.capitalize()
                    click.secho(
                        "%(field)s: %(message)s"
                        % {
                            "field": click.style(field, bold=True),
                            "message": click.style(v, fg="red"),
                        },
                        err=use_stderr,
                    )

        hint = get_error_hint(ctx, opts, exc)
        if hint:
            click.echo(
                "Hint: %(hint)s" % {"hint": click.style(hint, fg="yellow")},
                err=use_stderr,
            )

        if opts.verbose and not opts.debug:
            if exc.headers:
                click.echo(err=use_stderr)
                click.echo("Headers in Reply:", err=use_stderr)
                for k, v in six.iteritems(exc.headers):
                    click.echo(
                        "%(key)s = %(value)s" % {"key": k, "value": v}, err=use_stderr
                    )

        if reraise_on_error:
            six.reraise(*sys.exc_info())

        if exit_on_error:
            ctx.exit(exc.status or 1)
1185526
def get_location(self):
        
        response = self.connection.make_request('GET', self.name,
                                                query_args='location')
        body = response.read()
        if response.status == 200:
            rs = ResultSet(self)
            h = handler.XmlHandler(rs, self)
            xml.sax.parseString(body, h)
            return rs.LocationConstraint
        else:
            raise self.connection.provider.storage_response_error(
                response.status, response.reason, body)
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);
        }
    }
737653
def exception(cls, method, uri, response, message):
        
        # noinspection PyBroadException
        try:
            error_payload = json.loads(response.text)
            if 'message' in error_payload:
                message = '{}: {}'.format(message, error_payload['message'])
            code = error_payload.get('code', response.status_code)
            return TwilioRestException(response.status_code, uri, message, code, method)
        except Exception:
            return TwilioRestException(response.status_code, uri, message, response.status_code, method)
1218881
def get_location (host):
    
    if geoip is None:
        # no geoip available
        return None
    try:
        record = get_geoip_record(host)
    except (geoip_error, socket.error):
        log.debug(LOG_PLUGIN, "Geoip error for %r", host, exception=True)
        # ignore lookup errors
        return None
    value = u""
    if record and record.get("city"):
        value += unicode_safe(record["city"])
    if record and record.get("country_name"):
        if value:
            value += u", "
        value += unicode_safe(record["country_name"])
    return value
884840
def get_response(self, **kwargs):
        
        return Response(
            json.dumps({"error": self.message}),  # pylint: disable=exception-message-attribute
            status_code=self.status_code,
            content_type="application/json",
            charset="utf-8",
            **kwargs
        )
1200361
def get_body
      uri = URI.parse(@url)
      @response = get_response(uri)
      (@options[:any_response] || @response.code == '200') ? @response.body : nil
    rescue
      @options[:raise_error] ? raise : puts("Error: GET '#{@url}' -> #{$!.class}: #{$!.message}")
    end
912156
private static void ensureStatusOk(HttpResponse<String> response) throws ClientErrorException,
            ServerErrorException, OtherCommunicationException {
        int responseStatus = response.getStatus();
        if (isClientError(responseStatus)) {
            throw new ClientErrorException(response.getBody());
        } else if (isServerError(responseStatus)) {
            throw new ServerErrorException();
        } else if (isOtherErrorResponse(responseStatus)) {
            throw new OtherCommunicationException();
        }
    }
213099
def get(location, query_params = {})
      result = self.class.get(location, query_params)
      # FIXME: this is shit. should be based on on http response.
      if result['resultsPage']['error']
        msg = result['resultsPage']['error']['message']
        raise ResourceNotFound if msg =~ /not found/
        raise APIError.new(msg)
      end
      result
    end
951404
def handle_api_error(resp):
    """"""
    content = yield resp.json()

    headers = HeaderWrapper(resp.headers)

    try:
        err = content['error']
    except (KeyError, TypeError):
        raise error.APIError(
            "Invalid response object from API: %r (HTTP response code "
            "was %d)" % (content, resp.code),
            resp, resp.code, content, headers)

    if resp.code in [400, 404]:
        raise error.InvalidRequestError(
            err.get('message'), err.get('param'),
            resp, resp.code, content, headers)
    elif resp.code == 401:
        raise error.AuthenticationError(
            err.get('message'),
            resp, resp.code, content, headers)
    elif resp.code == 402:
        raise error.CardError(
            err.get('message'), err.get('param'), err.get('code'),
            content, resp.code, resp, headers)
    else:
        raise error.APIError(
            err.get('message'), content, resp.code, resp, headers)