Composes message of an error raised if the HTTP response doesn't
 correspond with expectation.
163959
def compose_error_message(http_response, max_len=200)
        msg = http_response.body.gsub("\n", ' ')
        msg = "#{msg[0..max_len]} ..." if msg.size > max_len
        msg
      end
268212
def _check_for_errors(response, json_response):
        
        status_code = response.status_code
        try:
            response.raise_for_status()
        except requests.HTTPError as why:
            raise ApiError(str(why), reply_code=status_code)
        if isinstance(json_response, dict) and 'error' in json_response:
            raise ApiError(json_response['error'], reply_code=status_code)
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)
931345
def check_for_errors(response) #:nodoc
      case response.status
        when 400 then raise HTTPRequestFailed, response.body
        when 403 then parse_403_error(response)
        when 404 then raise HTTPNotFound, response.body
        when 409 then raise RequestedIdentifierAlreadyExistsError, response.body
        when 410 then raise GoneError, response.body
        when 412 then raise PreconditionFailedError, response.body
        when 500 then raise BackendError, response.body
      end
    end
1169968
def handle_error(self,
                     request: BaseRequest,
                     status: int=500,
                     exc: Optional[BaseException]=None,
                     message: Optional[str]=None) -> StreamResponse:
        """"""
        self.log_exception("Error handling request", exc_info=exc)

        ct = 'text/plain'
        if status == HTTPStatus.INTERNAL_SERVER_ERROR:
            title = '{0.value} {0.phrase}'.format(
                HTTPStatus.INTERNAL_SERVER_ERROR
            )
            msg = HTTPStatus.INTERNAL_SERVER_ERROR.description
            tb = None
            if self.debug:
                with suppress(Exception):
                    tb = traceback.format_exc()

            if 'text/html' in request.headers.get('Accept', ''):
                if tb:
                    tb = html_escape(tb)
                    msg = '<h2>Traceback:</h2>\n<pre>{}</pre>'.format(tb)
                message = (
                    "<html><head>"
                    "<title>{title}</title>"
                    "</head><body>\n<h1>{title}</h1>"
                    "\n{msg}\n</body></html>\n"
                ).format(title=title, msg=msg)
                ct = 'text/html'
            else:
                if tb:
                    msg = tb
                message = title + '\n\n' + msg

        resp = Response(status=status, text=message, content_type=ct)
        resp.force_close()

        # some data already got sent, connection is broken
        if request.writer.output_size > 0 or self.transport is None:
            self.force_close()

        return resp
75149
def validate_response(response)
      case response
      when *SERVER_ERRORS
        raise ::Lgtm::Errors::UnexpectedError
      when *CLIENT_ERRORS
        raise ::Lgtm::Errors::UnexpectedError
      end
    end
689055
def error_handling(cls, fn):
        """"""
        def wrapper(*args, **kwargs):
            try:
                result = fn(*args, **kwargs)
                return result
            except InvalidRequestError as e:
                write_exception(e)

                if hasattr(e, 'request'):
                    write_error_message('request {0}'.format(repr(e.request)))
                if hasattr(e, 'response'):
                    write_error_message('response {0}'.format(repr(e.response)))

                raise e
        return wrapper
728263
def from_http_exception(cls, e):
        """"""
        assert isinstance(e, requests.exceptions.HTTPError)
        response = e.response
        try:
            message = response.json()['message']
        except (KeyError, ValueError):
            message = response.content.strip()

        raise cls(message)
568208
def _check_error(response):
        """"""
        if (not response.ok) or (response.status_code != 200):
            raise Exception(
                response.json()['error'] + ': ' +
                response.json()['error_description']
            )
167711
def onerror(self, message, source, lineno, colno):
        """"""
        return (message, source, lineno, colno)
213291
def ensure_success!(response)
      return if response.is_a? Net::HTTPSuccess

      message = "#{response.code} - #{response.message}"
      message += "\n#{response.body}" if response.body.present?

      raise Crapi::BadHttpResponseError, message
    end
66996
boolean isErrorResponse(HttpResponse response) {
        StatusLine status = response.getStatusLine();
        if (status == null || status.getStatusCode() != 200) {
            return true;
        }
        return false;
    }
1310337
function handleError(error, ignoreError) {
    appStore.setLoading(false)
    let reason

    if (error.response) {
        reason = handleResponseError(error)
    } else if (error.status >= 200 && error.status < 300) {
        reason = handleServiceError(error)
    } else {
        reason = handleRequestError(error)
    }

    if (ignoreError !== true) {
        appStore.setError(reason)
    }

    return Promise.reject(reason)
}
1059181
def _http_error_handler(http_error):
    ''' '''
    message = str(http_error)
    if http_error.respbody is not None:
        message += '\n' + http_error.respbody.decode('utf-8-sig')
    raise AzureHttpError(message, http_error.status)
647312
def error_message(response)
      method = response[:method].to_s.upcase
      url = response[:url].to_s
      status = response[:body][:status]
      error = response[:body][:error]
      "#{method} #{url}: #{status} - #{error}"
    end
1096894
def handle_error(self, request: Any, status: int = 500, exc: Any = None, message: Optional[str] = None) -> web.Response:
        """"""
        if self.transport is None:
            # client has been disconnected during writing.
            if self._access_log:
                request_ip = RequestHandler.get_request_ip(request, None)
                version_string = None
                if isinstance(request.version, HttpVersion):
                    version_string = 'HTTP/{}.{}'.format(request.version.major, request.version.minor)
                logging.getLogger('transport.http').info('[{}] [{}] {} {} "{} {}{}{}" - {} "{}" -'.format(
                    RequestHandler.colorize_status('http', 499),
                    RequestHandler.colorize_status(499),
                    request_ip or '',
                    '"{}"'.format(request._cache['auth'].login.replace('"', '')) if request._cache.get('auth') and getattr(request._cache.get('auth'), 'login', None) else '-',
                    request.method,
                    request.path,
                    '?{}'.format(request.query_string) if request.query_string else '',
                    ' {}'.format(version_string) if version_string else '',
                    request.content_length if request.content_length is not None else '-',
                    request.headers.get('User-Agent', '').replace('"', '')
                ))

        headers = {}
        headers[hdrs.CONTENT_TYPE] = 'text/plain; charset=utf-8'

        msg = '' if status == 500 or not message else message

        headers[hdrs.CONTENT_LENGTH] = str(len(msg))
        headers[hdrs.SERVER] = self._server_header or ''
        resp = web.Response(status=status,  # type: ignore
                            text=msg,
                            headers=headers)  # type: web.Response
        resp.force_close()  # type: ignore

        # some data already got sent, connection is broken
        if request.writer.output_size > 0 or self.transport is None:
            self.force_close()  # type: ignore
        elif self.transport is not None:
            request_ip = RequestHandler.get_request_ip(request, None)
            if not request_ip:
                peername = request.transport.get_extra_info('peername')
                if peername:
                    request_ip, _ = peername
            if self._access_log:
                logging.getLogger('transport.http').info('[{}] [{}] {} {} "INVALID" {} - "" -'.format(
                    RequestHandler.colorize_status('http', status),
                    RequestHandler.colorize_status(status),
                    request_ip or '',
                    '"{}"'.format(request._cache['auth'].login.replace('"', '')) if request._cache.get('auth') and getattr(request._cache.get('auth'), 'login', None) else '-',
                    len(msg)
                ))

        return resp
1016727
function HTTPError(statusCode, data) {
  Error.call(this);
  Error.captureStackTrace(this, this.constructor);

  /**
   * Human-readable error name.
   *
   * @type {String}
   */
  this.name = http.STATUS_CODES[statusCode];

  /**
   * HTTP status code.
   *
   * @type {Number}
   */
  this.statusCode = statusCode;

  /**
   * Any additional data.
   *
   * @type {*}
   */
  this.data = data;

  if (data) {
    // Property of Error.
    this.message = JSON.stringify(data);
  }
}