Raise client side exception(s) when present in the API response.

    Returned data is not modified.
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
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)
127937
def _assert_response_success(self, response):
        

        if response.status_code != self._STATUS_CODE_OK:
            raise ExceptionFactory.create_exception_for_response(
                response.status_code,
                self._fetch_all_error_message(response),
                self._fetch_response_id(response)
            )
378385
def _catch_index_error(self, response):
        
        code, headers, raw_data = response
        if not raw_data:
            return
        data = json.loads(raw_data)
        if not data or not data.get('errors'):
            return
        try:
            error_dict = data['items'][0]['index']
            message = error_dict['error']
        except (KeyError, IndexError):
            return
        raise exception_response(400, detail=message)
525989
def _raise_error(self, status_code, raw_data):
        
        error_message = raw_data
        additional_info = None
        try:
            if raw_data:
                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 (ValueError, TypeError) as err:
            logger.warning('Undecodable raw error response from server: %s', err)

        raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
1079327
def raise_invalid_type_exception(self):
        """"""
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err
1237167
def _raise_for_status(self, response):
        """"""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise create_api_error_from_http_exception(e)
202688
def raise_exception(self, node, exc=None, msg='', expr=None,
                        lineno=None):
        """"""
        if self.error is None:
            self.error = []
        if expr is None:
            expr = self.expr
        if len(self.error) > 0 and not isinstance(node, ast.Module):
            msg = '%s' % msg
        err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
        self._interrupt = ast.Break()
        self.error.append(err)
        if self.error_msg is None:
            self.error_msg = "at expr='%s'" % (self.expr)
        elif len(msg) > 0:
            self.error_msg = msg
        if exc is None:
            try:
                exc = self.error[0].exc
            except:
                exc = RuntimeError
        raise exc(self.error_msg)
1361416
def handle_exception(error):
        
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response
1157928
def exception(self, timeout=None, do_raise=True):
    

    with self._lock:
      self.wait(timeout, do_raise=do_raise)
      if not self._exc_info:
        return None
      self._exc_retrieved = True
      if self._cancelled:
        raise self.Cancelled()
      return self._exc_info[1]
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();
        }
    }
972712
def _handle_response(response):
        

        if not str(response.status_code).startswith('2'):
            raise KucoinAPIException(response)
        try:
            res = response.json()

            if 'code' in res and res['code'] != "200000":
                raise KucoinAPIException(response)

            if 'success' in res and not res['success']:
                raise KucoinAPIException(response)

            # by default return full response
            # if it's a normal response we have a data attribute, return that
            if 'data' in res:
                res = res['data']
            return res
        except ValueError:
            raise KucoinRequestException('Invalid Response: %s' % response.text)
1348152
def handle_exception(self, exc):
        """"""
        if isinstance(
            exc, (rest_exceptions.NotAuthenticated,
                  rest_exceptions.AuthenticationFailed)) and self.HANDLE_UNAUTHENTICATED:
            return HttpResponseRedirect('{}?next={}'.format(
                reverse('users:login'),
                self.request.get_full_path()))

        if isinstance(exc, Http404):
            raise Http404()

        if isinstance(exc, rest_exceptions.PermissionDenied):
            raise django_exceptions.PermissionDenied()

        return super().handle_exception(exc)
347769
def _handle_api_error(self, error):
        
        status_code = error.response.status_code
        message = error.message

        if 403 == status_code:
            raise NewRelicInvalidApiKeyException(message)
        elif 404 == status_code:
            raise NewRelicUnknownApplicationException(message)
        elif 422 == status_code:
            raise NewRelicInvalidParameterException(message)
        else:
            raise NewRelicApiException(message)
708803
def check_api_error(api_response):
    print(api_response)
    """"""
    if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200:
            print("Server response code: %s" % api_response['code'])
            print("Server response: %s" % api_response)
            raise exceptions.HTTPError('Unexpected response', response=api_response)
    if type(api_response) == dict and (api_response.get('status') == 'failed'):
        if 'ProgrammingError' in api_response.get('exception_cls'):
            raise DatabaseError(message='PyBossa database error.',
                                error=api_response)
        if ('DBIntegrityError' in api_response.get('exception_cls') and
            'project' in api_response.get('target')):
            msg = 'PyBossa project already exists.'
            raise ProjectAlreadyExists(message=msg, error=api_response)
        if 'project' in api_response.get('target'):
            raise ProjectNotFound(message='PyBossa Project not found',
                                  error=api_response)
        if 'task' in api_response.get('target'):
            raise TaskNotFound(message='PyBossa Task not found',
                               error=api_response)
        else:
            print("Server response: %s" % api_response)
            raise exceptions.HTTPError('Unexpected response', response=api_response)
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)
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)