Raise aiohttp exception and pass payload/reason into it.
491435
def _raise_exception(cls, reason, data=None):
    
    text_dict = {
        "error": reason
    }

    if data is not None:
        text_dict["errors"] = data

    raise cls(
        text=json.dumps(text_dict),
        content_type="application/json"
    )
1066643
def raise_(tp, value=None, tb=None):
    
    if value is not None and isinstance(tp, Exception):
        raise TypeError("instance exception may not have a separate value")
    if value is not None:
        exc = tp(value)
    else:
        exc = tp
    if exc.__traceback__ is not tb:
        raise exc.with_traceback(tb)
    raise exc
946590
def _raise_error(self, status_code, raw_data):
        
        error_message = raw_data
        additional_info = None
        try:
            additional_info = json.loads(raw_data)
            error_message = additional_info.get('error', error_message)
            if isinstance(error_message, dict) and 'type' in error_message:
                error_message = error_message['type']
        except:
            pass

        raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
1219442
def send_payload(self, params):
        """"""
        data = dumps({
            'jsonrpc': self.version,
            'method': self.service_name,
            'params': params,
            'id': str(uuid.uuid1())
        }).encode('utf-8')
        headers = {
            'Content-Type': 'application/json-rpc',
            'Accept': 'application/json-rpc',
            'Content-Length': len(data)
        }
        try:
            req = urllib_request.Request(self.service_url, data, headers)
            resp = urllib_request.urlopen(req)
        except IOError as e:
            if isinstance(e, urllib_error.HTTPError):
                if e.code not in (
                        401, 403
                ) and e.headers['Content-Type'] == 'application/json-rpc':
                    return e.read().decode('utf-8')  # we got a jsonrpc-formatted respnose
                raise ServiceProxyException(e.code, e.headers, req)
            else:
                raise e
        return resp.read().decode('utf-8')
812913
def _handle_exception(self, sender, exception=None):
        
        honeybadger.notify(exception)
        if self.reset_context_after_request:
            self._reset_context()
953187
async def makeHttpRequest(method, url, payload, headers, retries=utils.MAX_RETRIES, session=None):
    
    retry = -1
    response = None
    implicit = False
    if session is None:
        implicit = True
        session = aiohttp.ClientSession()

    def cleanup():
        if implicit:
            loop = asyncio.get_event_loop()
            loop.run_until_complete(session.close())

    try:
        while True:
            retry += 1
            # if this isn't the first retry then we sleep
            if retry > 0:
                snooze = float(retry * retry) / 10.0
                log.info('Sleeping %0.2f seconds for exponential backoff', snooze)
                await asyncio.sleep(snooze)

            # Seek payload to start, if it is a file
            if hasattr(payload, 'seek'):
                payload.seek(0)

            log.debug('Making attempt %d', retry)
            try:
                with async_timeout.timeout(60):
                    response = await makeSingleHttpRequest(method, url, payload, headers, session)
            except aiohttp.ClientError as rerr:
                if retry < retries:
                    log.warn('Retrying because of: %s' % rerr)
                    continue
                # raise a connection exception
                raise rerr
            except ValueError as rerr:
                log.warn('ValueError from aiohttp: redirect to non-http or https')
                raise rerr
            except RuntimeError as rerr:
                log.warn('RuntimeError from aiohttp: session closed')
                raise rerr
            # Handle non 2xx status code and retry if possible
            status = response.status
            if 500 <= status and status < 600 and retry < retries:
                if retry < retries:
                    log.warn('Retrying because of: %d status' % status)
                    continue
                else:
                    raise exceptions.TaskclusterRestFailure("Unknown Server Error", superExc=None)
            return response
    finally:
        cleanup()
    # This code-path should be unreachable
    assert False, "Error from last retry should have been raised!"
804497
def _raise_rpc_timeout_error(self, uuid):
        
        requests = []
        for key, value in self._request.items():
            if value == uuid:
                requests.append(key)
        self.remove(uuid)
        message = (
            'rpc requests %s (%s) took too long' %
            (
                uuid,
                ', '.join(requests)
            )
        )
        raise AMQPChannelError(message)
636658
def do_raise(self, arg):
        """"""
        self.do_continue(arg)

        # Annotating the exception for a continual re-raise
        _, exc_value, _ = self.exc_info
        exc_value._ipdbugger_let_raise = True

        raise_(*self.exc_info)
349487
def raise_api_exceptions(function, *args, **kwargs):
    
    try:
        return_value = function(*args, **kwargs)
    except errors.HTTPException as exc:
        if exc._raw.status_code != 400:  # pylint: disable=W0212
            raise  # Unhandled HTTPErrors
        try:  # Attempt to convert v1 errors into older format (for now)
            data = exc._raw.json()  # pylint: disable=W0212
            assert len(data) == 2
            return_value = {'errors': [(data['reason'],
                                        data['explanation'], '')]}
        except Exception:
            raise exc
    if isinstance(return_value, dict):
        if return_value.get('error') == 304:  # Not modified exception
            raise errors.NotModified(return_value)
        elif return_value.get('errors'):
            error_list = []
            for error_type, msg, value in return_value['errors']:
                if error_type in errors.ERROR_MAPPING:
                    if error_type == 'RATELIMIT':
                        args[0].evict(args[1])
                    error_class = errors.ERROR_MAPPING[error_type]
                else:
                    error_class = errors.APIException
                error_list.append(error_class(error_type, msg, value,
                                              return_value))
            if len(error_list) == 1:
                raise error_list[0]
            else:
                raise errors.ExceptionList(error_list)
    return return_value
34863
def _raise_exception(self, eobj, edata=None):
        """"""
        _, _, tbobj = sys.exc_info()
        if edata:
            emsg = self._format_msg(eobj["msg"], edata)
            _rwtb(eobj["type"], emsg, tbobj)
        else:
            _rwtb(eobj["type"], eobj["msg"], tbobj)
258412
def request_error!(exception)
      case exception
      when HTTP::Request::UnsupportedSchemeError, Addressable::URI::InvalidURIError
        raise Down::InvalidUrl, exception.message
      when HTTP::ConnectionError
        raise Down::ConnectionError, exception.message
      when HTTP::TimeoutError
        raise Down::TimeoutError, exception.message
      when HTTP::Redirector::TooManyRedirectsError
        raise Down::TooManyRedirects, exception.message
      when OpenSSL::SSL::SSLError
        raise Down::SSLError, exception.message
      else
        raise exception
      end
    end
398214
def exception(self, *args, **kwargs):
        """"""
        kwargs['api'] = self.api
        return exception(*args, **kwargs)
442400
def handle_api_exceptions_inter(self, method, *url_parts, **kwargs):
        """"""
        global request_count  # used only in single thread tests - OK # pylint:disable=global-statement
        # log.info("request %s %s", method, '/'.join(url_parts))
        # import pdb; pdb.set_trace()  # NOQA
        api_ver = kwargs.pop('api_ver', None)
        url = self.rest_api_url(*url_parts, api_ver=api_ver)
        # The 'verify' option is about verifying TLS certificates
        kwargs_in = {'timeout': getattr(settings, 'SALESFORCE_QUERY_TIMEOUT', (4, 15)),
                     'verify': True}
        kwargs_in.update(kwargs)
        log.debug('Request API URL: %s', url)
        request_count += 1
        session = self.sf_session

        try:
            response = session.request(method, url, **kwargs_in)
        except requests.exceptions.Timeout:
            raise SalesforceError("Timeout, URL=%s" % url)
        if response.status_code == 401:  # Unauthorized
            # Reauthenticate and retry (expired or invalid session ID or OAuth)
            if ('json' in response.headers['content-type']
                    and response.json()[0]['errorCode'] == 'INVALID_SESSION_ID'):
                token = session.auth.reauthenticate()
                if 'headers' in kwargs:
                    kwargs['headers'].update(Authorization='OAuth %s' % token)
                try:
                    response = session.request(method, url, **kwargs_in)
                except requests.exceptions.Timeout:
                    raise SalesforceError("Timeout, URL=%s" % url)

        if response.status_code < 400:  # OK
            # 200 "OK" (GET, POST)
            # 201 "Created" (POST)
            # 204 "No Content" (DELETE)
            # 300 ambiguous items for external ID.
            # 304 "Not Modified" (after conditional HEADER request for metadata),
            return response
        # status codes docs (400, 403, 404, 405, 415, 500)
        # https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/errorcodes.htm
        self.raise_errors(response)
798664
def handle_exception(self, e, request=None):
        
        if isinstance(e, HttpError):
            response = SerializedHttpResponse(e.content, status=e.status)
            return self.emit(
                response, request=request, emitter=e.emitter)

        if isinstance(e, (AssertionError, ValidationError)):

            content = unicode(e)

            if isinstance(e, FormError):
                content = e.form.errors

            response = SerializedHttpResponse(
                content, status=status.HTTP_400_BAD_REQUEST)

            return self.emit(response, request=request)

        if ADREST_DEBUG:
            raise

        logger.exception('\nADREST API Error: %s', request.path)

        return HttpResponse(str(e), status=500)
86696
async def _handle_exception(self, e, sock):
        
        if isinstance(e, (RemoteProtocolError, AssertionError)):
            await sock.close()
            raise BadHttpResponse('Invalid HTTP response from server.') from e

        if isinstance(e, Exception):
            await sock.close()
            raise e
983441
def raise_for_status(self):
        """"""

        if self.error:
            raise self.error

        if (self.status_code >= 300) and (self.status_code < 400):
            raise HTTPError('%s Redirection' % self.status_code)

        elif (self.status_code >= 400) and (self.status_code < 500):
            raise HTTPError('%s Client Error' % self.status_code)

        elif (self.status_code >= 500) and (self.status_code < 600):
            raise HTTPError('%s Server Error' % self.status_code)
278773
def _raise_timeout(self, err, url, timeout_value):
        """"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python < 2.7.4
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)