raise a descriptive exception on a "bad request" response
490862
def check_response(self, resp):
        """"""
        if resp.status_code == 400:
            raise ApiException(json.loads(resp.content).get('message'))
        return resp
300155
def response_error!(response)
      code    = response.code.to_i
      message = response.message.split(" ").map(&:capitalize).join(" ")

      args = ["#{code} #{message}", response: response]

      case response.code.to_i
      when 400..499 then raise Down::ClientError.new(*args)
      when 500..599 then raise Down::ServerError.new(*args)
      else               raise Down::ResponseError.new(*args)
      end
    end
725861
def _handle_response(self, response):
        
        if not str(response.status_code).startswith('2'):
            raise build_api_error(response)
        return response
791589
def handle_exception(e)
    raise e unless defined?(e.response) && e.response != nil

    code = e.response[:status]
    error = Nokogiri::XML(e.response[:body])

    message = if error.xpath("m:error/m:message", @ds_namespaces).first
                error.xpath("m:error/m:message", @ds_namespaces).first.content
              else
                "Server returned error but no message."
              end
    raise ServiceError.new(code), message
  end
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)
74361
def error_handler(exception_cls, response):
    """"""
    # Responses are sent as html. Split on the newlines and give us
    # the <p> text back.
    error = convert_response_to_text(response)
    exception = exception_cls("Response Code: %s\tResponse: %s" %
                              (response.status_code, error))
    exception.status_code = response.status_code
    raise exception
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)
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
34413
def failed_request_exception(message, r):
    """"""
    try:
        resp = json.loads(r.text)
        message = '%s: %d\n%s' % (message, resp['error']['code'],
                                  resp['error']['message'])
        return click.ClickException(message)
    except ValueError:
        # fallback on raw text response if error is not structured.
        return click.ClickException('%s: %d\n%s' % (message,
                                                    r.status_code,
                                                    r.text))
516291
private BadRequestException getBadRequestException(Exception ex) {
	    return (BadRequestException) ExceptionUtils
	            .getThrowables(ex)[ExceptionUtils.indexOfThrowable(ex, BadRequestException.class)];
	}
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)
677887
def build_from_invalid_request(cls, invalid_request_object):
        """"""
        errors = [{err['parameter']: err['message']} for err in invalid_request_object.errors]
        return cls.build_response(Status.UNPROCESSABLE_ENTITY, errors)
366132
public void badRequest(final BadRequestException exception) {
    logWarn("Bad Request on " + request().getUri() + ": " + exception.getMessage());
    sendBuffer(HttpResponseStatus.BAD_REQUEST,
        ChannelBuffers.wrappedBuffer(
            exception.toString().getBytes(Const.UTF8_CHARSET)),
        "text/plain");
  }
114009
def request_exception(sender, request, **kwargs):
    
    if not isinstance(request, WSGIRequest):
        logger = logging.getLogger(__name__)
        level = CRITICAL if request.status_code <= 500 else WARNING

        logger.log(level, '%s exception occured (%s)',
                   request.status_code, request.reason_phrase)

    else:
        logger = logging.getLogger(__name__)
        logger.log(WARNING, 'WSGIResponse exception occured')
1206839
def proc_response(self, resp):
        

        # Raise exceptions for error responses
        if resp.status >= 400:
            e = exc.exception_map.get(resp.status, exc.HTTPException)
            self._debug("  Response was a %d fault, raising %s",
                        resp.status, e.__name__)
            raise e(resp)
581055
private static void renderException(final Map model, final HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        model.put("status", HttpServletResponse.SC_BAD_REQUEST);
        render(model, response);
    }
380390
def http_exception(channel, title):
    

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Too much help",
        "{} is too helpful! Try trimming some of the help messages.".format(title),
        modulename=modulename
    )

    return gui