Add json_error_formatter to any webob HTTPExceptions.
170693
def call_func(self, req, *args, **kwargs):
        """"""
        try:
            return super(SdkWsgify, self).call_func(req, *args, **kwargs)
        except webob.exc.HTTPException as exc:
            msg = ('encounter %(error)s error') % {'error': exc}
            LOG.debug(msg)
            exc.json_formatter = json_error_formatter
            code = exc.status_int
            explanation = six.text_type(exc)

            fault_data = {
                'overallRC': 400,
                'rc': 400,
                'rs': code,
                'modID': SDKWSGI_MODID,
                'output': '',
                'errmsg': explanation}
            exc.text = six.text_type(json.dumps(fault_data))
            raise exc
691742
def errors(self,
               errors: List[str],
               code: Union[int, Tuple[int, str, str]] = HTTPStatus.BAD_REQUEST,
               key: str = 'errors',
               headers: Optional[Dict[str, str]] = None,
               ):
        
        return jsonify({key: errors}), code, headers or {}
838996
protected void returnJsonSystemError(HttpServletRequest request, HttpServletResponse response,
            ResultCode resultCode) throws IOException {
        Map<String, Object> errors = new HashMap<String, Object>();
        errors.put(WebResponseConstant.MESSAGE_GLOBAL, resultCode.getMessage().getMessage());
        JsonObject<?> json = JsonObject.create();
        json.setStatus(resultCode.getCode());
        json.setStatusInfo(errors);
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JsonUtils.toJson(json));
    }
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)
117490
function(err) {

        var message = 'Error occured while performing a JSON-WSP request. ' +
            err.message + '\n' +
            JSON.stringify({
                options : curOpts
            }, null, '  ').yellow;

        logger.error(message);
    }
692840
def http_error_default(self, url, fp, errcode, errmsg, headers):
        """"""
        return addinfourl(fp, headers, "http:" + url, errcode)
687643
def write_error(self, status_code, **kwargs):
        """"""
        message = default_message = httplib.responses.get(status_code, '')
        # HTTPError exceptions may have a log_message attribute
        if 'exc_info' in kwargs:
            (_, exc, _) = kwargs['exc_info']
            if hasattr(exc, 'log_message'):
                message = str(exc.log_message) or default_message
        self.logvalue('halt_reason', message)
        title = "{}: {}".format(status_code, default_message)
        body = "{}: {}".format(status_code, message)
        self.finish("<html><title>" + title + "</title>"
                    "<body>" + body + "</body></html>")
1078179
def errors_to_json(errors):
    """"""
    out = []
    for e in errors:
        out.append({
            "check": e[0],
            "message": e[1],
            "line": 1 + e[2],
            "column": 1 + e[3],
            "start": 1 + e[4],
            "end": 1 + e[5],
            "extent": e[6],
            "severity": e[7],
            "replacements": e[8],
        })

    return json.dumps(
        dict(status="success", data={"errors": out}), sort_keys=True)
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"
    )
1337128
def __check_http_err(self, status_code):
        """"""
        if status_code == 403:
            raise exceptions.APIAuthenticationError(self.api_key)
        elif status_code == 503:
            raise exceptions.APITimeoutError()
        else:
            return False
989665
def FormatException(self, e, output):
    """"""
    d = e.GetDictToFormat()
    for k in ('file_name', 'feedname', 'column_name'):
      if k in d.keys():
        d[k] = '<code>%s</code>' % d[k]
    if 'url' in d.keys():
      d['url'] = '<a href="%(url)s">%(url)s</a>' % d

    problem_text = e.FormatProblem(d).replace('\n', '<br>')
    problem_class = 'problem'
    if e.IsNotice():
      problem_class += ' notice'
    output.append('<li>')
    output.append('<div class="%s">%s</div>' %
                  (problem_class, transitfeed.EncodeUnicode(problem_text)))
    try:
      if hasattr(e, 'row_num'):
        line_str = 'line %d of ' % e.row_num
      else:
        line_str = ''
      output.append('in %s<code>%s</code><br>\n' %
                    (line_str, transitfeed.EncodeUnicode(e.file_name)))
      row = e.row
      headers = e.headers
      column_name = e.column_name
      table_header = ''  # HTML
      table_data = ''  # HTML
      for header, value in zip(headers, row):
        attributes = ''
        if header == column_name:
          attributes = ' class="problem"'
        table_header += '<th%s>%s</th>' % (attributes, header)
        table_data += '<td%s>%s</td>' % (attributes, value)
      # Make sure output is encoded into UTF-8
      output.append('<table class="dump"><tr>%s</tr>\n' %
                    transitfeed.EncodeUnicode(table_header))
      output.append('<tr>%s</tr></table>\n' %
                    transitfeed.EncodeUnicode(table_data))
    except AttributeError as e:
      pass  # Hope this was getting an attribute from e ;-)
    output.append('<br></li>\n')
1059032
function formatError(e) {
  if (!e.err) return e.message;
  if (e.err.message) return e.err.message;
  return JSON.stringify(e.err);
}
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
81846
def format_error(err_type, err_value, err_trace=None):
    """"""
    if err_trace is None:
        err_parts = "".join(traceback.format_exception_only(err_type, err_value)).strip().split(": ", 1)
        if len(err_parts) == 1:
            err_name, err_msg = err_parts[0], ""
        else:
            err_name, err_msg = err_parts
        err_name = err_name.split(".")[-1]
        return err_name + ": " + err_msg
    else:
        return "".join(traceback.format_exception(err_type, err_value, err_trace)).strip()
728263
def from_http_exception(cls, e):
        """"""
        assert isinstance(e, requests.exceptions.HTTPError)
        response = e.response
        try:
            message = response.json()['message']
        except (KeyError, ValueError):
            message = response.content.strip()

        raise cls(message)
812649
def _adapt_response(self, response):
        """"""
        if 'application/json' in response.headers['content-type']:
            body = response.json()
            status = response.status_code

            if body.get('error'):
                return self._simple_response_to_error_adapter(status, body)

        raise UnknownHttpError(response)
965417
def __parseForException(self, http_error):
        
        data = http_error.body
        try:
            if isinstance(data, str):
                data = cjson.decode(data)
        except:
            raise http_error

        if isinstance(data, dict) and 'exception' in data:# re-raise with more details
            raise HTTPError(http_error.url, data['exception'], data['message'], http_error.header, http_error.body)

        raise http_error