Raise appropriate error when bad response received.
198051
def raise_right_error(response):
    """"""
    if response.status_code == 200:
        return
    if response.status_code == 500:
        raise ServerError('Clef servers are down.')
    if response.status_code == 403:
        message = response.json().get('error')
        error_class = MESSAGE_TO_ERROR_MAP[message]
        if error_class == InvalidOAuthTokenError:
            message = 'Something went wrong at Clef. Unable to retrieve user information with this token.'
        raise error_class(message)
    if response.status_code == 400:
        message = response.json().get('error')
        error_class = MESSAGE_TO_ERROR_MAP[message]
        if error_class:
            raise error_class(message)
        else:
            raise InvalidLogoutTokenError(message)
    if response.status_code == 404:
        raise NotFoundError('Unable to retrieve the page. Are you sure the Clef API endpoint is configured right?')
    raise APIError
729117
def _conditional_error(self, req, response):
        
        if not req or req.sent_headers:
            return

        try:
            req.simple_response(response)
        except errors.FatalSSLAlert:
            pass
        except errors.NoSSLError:
            self._handle_no_ssl(req)
792659
def handle_error(_, client_addr):
        """"""
        exc_type, exc_value, _ = sys.exc_info()
        if exc_type is socket.error and exc_value[0] == 32:
            pass
        elif exc_type is cPickle.UnpicklingError:
            sys.stderr.write('Invalid connection from {0}\n'
                             .format(client_addr[0]))
        else:
            raise
305361
function handleErrors(errorFormatter, response) {
  if (!response.ok) {
    if (errorFormatter) {
      return errorFormatter(response);
    }

    return defaultErrorFormatter(response);
  }
  return response;
}
212818
def _raise_fail(self, response, expected):
        
        try:
            if self.logger:
                self.logger.error("Status code "
                                  "{} != {}. \n\n "
                                  "Payload: {}".format(response.status_code,
                                                       expected,
                                                       response.content))
            raise TestStepFail("Status code {} != {}.".format(response.status_code, expected))
        except TestStepFail:
            raise
        except:  # pylint: disable=bare-except
            if self.logger:
                self.logger.error("Status code "
                                  "{} != {}. \n\n "
                                  "Payload: {}".format(response.status_code,
                                                       expected,
                                                       "Unable to parse payload"))
            raise TestStepFail("Status code {} != {}.".format(response.status_code, expected))
1320088
def raise_for_status(self):
        """"""
        if 400 <= self.status_code < 600:
            message = 'Error %s for %s' % (self.status_code, self.url)
            raise HTTPError(message)
1230743
def validate(response)
      case response.code
        when 400; raise Error::BadRequest.new error_message(response)
        when 401; raise Error::Unauthorized.new error_message(response)
        when 403; raise Error::Forbidden.new error_message(response)
        when 404; raise Error::NotFound.new error_message(response)
        when 405; raise Error::MethodNotAllowed.new error_message(response)
        when 409; raise Error::Conflict.new error_message(response)
        when 500; raise Error::InternalServerError.new error_message(response)
        when 502; raise Error::BadGateway.new error_message(response)
        when 503; raise Error::ServiceUnavailable.new error_message(response)
      end

      response.parsed_response
    end
662196
def handle_error(self, msgtype, msgid, error):
        """"""
        self._proxy.error(msgid, error)
235265
def expect_invalid_resp_data(data=''):
    """"""
    try:
        yield
    except (ValueError, TypeError, IndexError, AttributeError,
            KeyError) as err:
        msg = ('Invalid smt response data: %s. Error: %s' %
               (data, six.text_type(err)))
        LOG.error(msg)
        raise exception.SDKInternalError(msg=msg)
1325797
def _handle_rate_exceeded(self, response):  # pragma: no cover
        """"""
        waiting_time = int(response.headers.get("Retry-After", 10))
        time.sleep(waiting_time)
1072820
def _raise_for_status(self, response, explanation=None):
        """"""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                raise errors.NotFound(e, response, explanation=explanation)
            raise errors.APIError(e, response, explanation=explanation)
860521
def _handle_http_errors(response):
    
    code = response.status_code
    if 200 <= code < 400:
        return response
    elif code in (403, 404):
        raise {403: _ObjectPermissionError,
               404: _ObjectNotFoundError}[code](response.reason)
    response.raise_for_status()
932164
def raise_errors(self, response):
        """"""
        # Errors: 400, 403 permissions or REQUEST_LIMIT_EXCEEDED, 404, 405, 415, 500)
        # TODO extract a case ID for Salesforce support from code 500 messages

        # TODO disabled 'debug_verbs' temporarily, after writing better default messages
        verb = self.debug_verbs  # NOQA pylint:disable=unused-variable
        method = response.request.method
        data = None
        is_json = 'json' in response.headers.get('Content-Type', '') and response.text
        if is_json:
            data = json.loads(response.text)
        if not (isinstance(data, list) and data and 'errorCode' in data[0]):
            messages = [response.text] if is_json else []
            raise OperationalError(
                ['HTTP error "%d %s":' % (response.status_code, response.reason)]
                + messages, response, ['method+url'])

        # Other Errors are reported in the json body
        err_msg = data[0]['message']
        err_code = data[0]['errorCode']
        if response.status_code == 404:  # ResourceNotFound
            if method == 'DELETE' and err_code in ('ENTITY_IS_DELETED', 'INVALID_CROSS_REFERENCE_KEY'):
                # It was a delete command and the object is in trash bin or it is
                # completely deleted or it could be a valid Id for this sobject type.
                # Then we accept it with a warning, similarly to delete by a classic database query:
                # DELETE FROM xy WHERE id = 'something_deleted_yet'
                warn_sf([err_msg, "Object is deleted before delete or update"], response, ['method+url'])
                # TODO add a warning and add it to messages
                return None
        if err_code in ('NOT_FOUND',           # 404 e.g. invalid object type in url path or url query?q=select ...
                        'METHOD_NOT_ALLOWED',  # 405 e.g. patch instead of post
                        ):                     # both need to report the url
            raise SalesforceError([err_msg], response, ['method+url'])
        # it is good e.g for these errorCode: ('INVALID_FIELD', 'MALFORMED_QUERY', 'INVALID_FIELD_FOR_INSERT_UPDATE')
        raise SalesforceError([err_msg], response)
966770
def check_error(self, response):
        
        if response.status_code == 500:
            raise ServiceError("500 - " + response.content)

        if response.status_code == 503:
            if "DDoS protection by Cloudflare" in response.content:
                raise ServiceError("Foiled by Cloudfare's DDoS protection")
            raise ServiceError("503 - Temporarily out of service.")

        if response.status_code == 429:
            raise ServiceError("429 - Too many requests")

        if response.status_code == 404:
            raise ServiceError("404 - Not Found")

        if response.status_code == 400:
            raise ServiceError("400 - Bad Request")
209961
function raise(err, parameters, cause) {
  if(!(err instanceof Error)) {
    err = wrap(err, parameters, cause);
  }
  throw err;
}
605472
def _raise_on_error(data: Union[str, dict]) -> None:
    """"""
    if isinstance(data, str):
        raise_error(data)
    elif 'status' in data and data['status'] != 'success':
        raise_error(data['data']['message'])
271477
def _raise_for_status(response):
    
    message = ''
    if 400 <= response.status < 500:
        message = '%s Client Error: %s' % (response.status, response.reason)
    elif 500 <= response.status < 600:
        message = '%s Server Error: %s' % (response.status, response.reason)
    else:
        return
    if response.status == 503:
        raise ConnectionError(message)
    if response.headers.get("content-type", "").startswith("application/json"):
        data = json.loads(response.data.decode('utf-8'))
        error = data.get('error', {})
        error_trace = data.get('error_trace', None)
        if "results" in data:
            errors = [res["error_message"] for res in data["results"]
                      if res.get("error_message")]
            if errors:
                raise ProgrammingError("\n".join(errors))
        if isinstance(error, dict):
            raise ProgrammingError(error.get('message', ''),
                                   error_trace=error_trace)
        raise ProgrammingError(error, error_trace=error_trace)
    raise ProgrammingError(message)