Re-raise Net::HTTP exceptions as Down::Error exceptions.
515377
def request_error!(exception)
      case exception
      when Net::OpenTimeout
        raise Down::TimeoutError, "timed out waiting for connection to open"
      when Net::ReadTimeout
        raise Down::TimeoutError, "timed out while reading data"
      when EOFError, IOError, SocketError, SystemCallError
        raise Down::ConnectionError, exception.message
      when OpenSSL::SSL::SSLError
        raise Down::SSLError, exception.message
      else
        raise exception
      end
    end
453521
def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
        """"""
        return self.http_error_302(url, fp, errcode, errmsg, headers, data)
1197588
def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
        """"""
        if data is None:
            return self.http_error_302(url, fp, errcode, errmsg, headers, data)
        else:
            return self.http_error_default(url, fp, errcode, errmsg, headers)
1270852
def _http_error_handler(http_error):
    ''' '''
    message = str(http_error)
    error_code = None

    if 'x-ms-error-code' in http_error.respheader:
        error_code = http_error.respheader['x-ms-error-code']
        message += ' ErrorCode: ' + error_code

    if http_error.respbody is not None:
        message += '\n' + http_error.respbody.decode('utf-8-sig')

    ex = AzureHttpError(message, http_error.status)
    ex.error_code = error_code

    raise ex
776345
def errorhandle(self, resp):            
        """"""
        if self.format == 'json':
            parsed = xmltodict.parse(resp)
            errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN]
            # Create list of errors if more than one error response is given
            if type(errors) is list and len(errors) > 1:
                messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors])
            else:
                overlimit = any('transaction limit' in msg.lower() for msg in errors.values())
                if overlimit:
                    raise APILimitExceeded("This API key has used up its daily quota of calls.")
                else:    
                    messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()])    
        elif self.format == 'xml':
            import xml.etree.ElementTree as ET
            errors = ET.fromstring(resp).findall(self.ERROR_TOKEN)
            messages = ", ".join(err.find('msg').text for err in errors)
        else:
            raise ValueError("Invalid API response format specified: {}." % self.format)        
        
        raise BustimeError("API returned: {}".format(messages))
726316
def request_failed exception, req, connection # :nodoc:
    due_to = "(due to #{exception.message} - #{exception.class})"
    message = "too many connection resets #{due_to} #{error_message connection}"

    finish connection

    raise Error, message, exception.backtrace
  end
642620
def bunny_exceptions
      [
        Bunny::ConnectionError, Bunny::ForcedChannelCloseError, Bunny::ForcedConnectionCloseError,
        Bunny::MessageError, Bunny::ProtocolError, Bunny::ServerDownError, Bunny::UnsubscribeError,
        Bunny::AcknowledgementError, Qrack::BufferOverflowError, Qrack::InvalidTypeError,
        Errno::EHOSTUNREACH, Errno::ECONNRESET, Timeout::Error
      ]
    end
276253
def raise_api_error(resp, state=None):
    """"""
    # TODO: Refactor into an Exception class
    error_code = resp.status_code

    if error_code == 402:
        error_message = (
            "Please add a payment method to upload more samples. If you continue to "
            "experience problems, contact us at help@onecodex.com for assistance."
        )
    elif error_code == 403:
        error_message = "Please login to your One Codex account or pass the appropriate API key."
    else:
        try:
            error_json = resp.json()
        except ValueError:
            error_json = {}

        if "msg" in error_json:
            error_message = error_json["msg"].rstrip(".")
        elif "message" in error_json:
            error_message = error_json["message"].rstrip(".")
        else:
            error_message = None

        if state == "init" and not error_message:
            error_message = (
                "Could not initialize upload. Are you logged in? If this problem "
                "continues, please contact help@onecodex.com for assistance."
            )
        elif state == "upload" and not error_message:
            error_message = (
                "File could not be uploaded. If this problem continues, please contact "
                "help@onecodex.com for assistance."
            )
        elif state == "callback" and not error_message:
            error_message = (
                "Callback could not be completed. If this problem continues, please "
                "contact help@onecodex.com for assistance."
            )

    if error_message is None:
        error_message = "Upload failed. Please contact help@onecodex.com for assistance."

    raise UploadException(error_message)
512301
def _error_handling(self, res):
        

        # making the error handling generic so if an status_code starting with 2 doesn't exist, we raise the error
        if res.status_code // 100 != 2:
            error = self._get_response_json(res)
            raise exceptions.KeenApiError(error)
502448
def _raise_response_exceptions(response):
    """"""
    if not response.ok and 'www-authenticate' in response.headers:
        msg = response.headers['www-authenticate']
        if 'insufficient_scope' in msg:
            raise OAuthInsufficientScope('insufficient_scope', response.url)
        elif 'invalid_token' in msg:
            raise OAuthInvalidToken('invalid_token', response.url)
        else:
            raise OAuthException(msg, response.url)

    if response.status_code == codes.forbidden:  # pylint: disable=E1101
        raise Forbidden(_raw=response)
    elif response.status_code == codes.not_found:  # pylint: disable=E1101
        raise NotFound(_raw=response)
    else:
        try:
            response.raise_for_status()  # These should all be directly mapped
        except exceptions.HTTPError as exc:
            raise HTTPException(_raw=exc.response)
731202
def raise_error(self, status=500, message="Generic server error.  Out of luck..."):
        
        self.set_status(status)
        self.write({"message" : message,
                    "status" : status})
780881
def rewrite_exception(old_name, new_name):
    """"""
    try:
        yield
    except Exception as e:
        msg = e.args[0]
        msg = msg.replace(old_name, new_name)
        args = (msg,)
        if len(e.args) > 1:
            args = args + e.args[1:]
        e.args = args
        raise
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)
898151
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
        """"""
        self.tries += 1
        if self.maxtries and self.tries >= self.maxtries:
            if hasattr(self, "http_error_500"):
                meth = self.http_error_500
            else:
                meth = self.http_error_default
            self.tries = 0
            return meth(url, fp, 500,
                        "Internal Server Error: Redirect Recursion", headers)
        result = self.redirect_internal(url, fp, errcode, errmsg, headers,
                                        data)
        self.tries = 0
        return result
1317394
def _raise_for_status(response):
    '''
    
    '''
    http_error_msg = ""

    if 400 <= response.status_code < 500:
        http_error_msg = "{0} Client Error: {1}".format(response.status_code,
                                                        response.reason)

    elif 500 <= response.status_code < 600:
        http_error_msg = "{0} Server Error: {1}".format(response.status_code,
                                                        response.reason)

    if http_error_msg:
        try:
            more_info = response.json().get("message")
        except ValueError:
            more_info = None
        if more_info and more_info.lower() != response.reason.lower():
            http_error_msg += ".\n\t{0}".format(more_info)
        raise requests.exceptions.HTTPError(http_error_msg, response=response)
918841
def RetryOnUnavailable(func):
  """"""

  @functools.wraps(func)
  def Wrapper(*args, **kwargs):
    while True:
      try:
        response = func(*args, **kwargs)
      except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
        time.sleep(5)
        if (isinstance(e, urlerror.HTTPError)
            and e.getcode() == httpclient.SERVICE_UNAVAILABLE):
          continue
        elif isinstance(e, socket.timeout):
          continue
        raise
      else:
        if response.getcode() == httpclient.OK:
          return response
        else:
          raise StatusException(response)
  return Wrapper
554783
def raise_exception(self, original_exception=None):
        
        if self._executed_retries < self._max_retries:
            curr_backoff = self._ms_backoff
            self._executed_retries += 1
            self._ms_backoff = self._ms_backoff * 2
            raise ActionRetryException(curr_backoff)
        else:
            raise original_exception or Exception()