return the Exception data in a format for JSON-RPC
502851
def json_rpc_format(self):
        

        error = {
            'name': smart_text(self.__class__.__name__),
            'code': self.code,
            'message': "%s: %s" %
            (smart_text(self.__class__.__name__), smart_text(self.message)),
            'data': self.data
        }

        from django.conf import settings

        if settings.DEBUG:
            import sys, traceback
            error['stack'] = traceback.format_exc()
            error['executable'] = sys.executable

        return error
434744
def json(self, **kwargs):
        
        try:
            return super(ScraperResponse, self).json(**kwargs)
        except ValueError as ve:
            raise ParseException(ve)
1059032
function formatError(e) {
  if (!e.err) return e.message;
  if (e.err.message) return e.err.message;
  return JSON.stringify(e.err);
}
305537
def get_exception_message(instance):
    ''''''
    args = getattr(instance, 'args', None)

    if args:
        return str(instance)

    try:
        return type(instance).__name__
    except AttributeError:
        return str(instance)
715297
def _get_exceptions_db(self):
        """"""
        template = "{extype} ({exmsg}){raised}"
        if not self._full_cname:
            # When full callable name is not used the calling path is
            # irrelevant and there is no function associated with an
            # exception
            ret = []
            for _, fdict in self._ex_dict.items():
                for key in fdict.keys():
                    ret.append(
                        {
                            "name": fdict[key]["name"],
                            "data": template.format(
                                extype=_ex_type_str(key[0]),
                                exmsg=key[1],
                                raised="*" if fdict[key]["raised"][0] else "",
                            ),
                        }
                    )
            return ret
        # When full callable name is used, all calling paths are saved
        ret = []
        for fdict in self._ex_dict.values():
            for key in fdict.keys():
                for func_name in fdict[key]["function"]:
                    rindex = fdict[key]["function"].index(func_name)
                    raised = fdict[key]["raised"][rindex]
                    ret.append(
                        {
                            "name": self.decode_call(func_name),
                            "data": template.format(
                                extype=_ex_type_str(key[0]),
                                exmsg=key[1],
                                raised="*" if raised else "",
                            ),
                        }
                    )
        return ret
1080076
def find_json(raw):
    '''
    
    '''
    ret = {}
    lines = __split(raw)
    for ind, _ in enumerate(lines):
        try:
            working = '\n'.join(lines[ind:])
        except UnicodeDecodeError:
            working = '\n'.join(salt.utils.data.decode(lines[ind:]))

        try:
            ret = json.loads(working)  # future lint: blacklisted-function
        except ValueError:
            continue
        if ret:
            return ret
    if not ret:
        # Not json, raise an error
        raise ValueError
785536
def rest_error(self):
    
    error_json = self.__format_error('errors')
    return json.dumps(error_json, indent=1, sort_keys=True)
322839
public String getJsonError(ODataException exception) throws ODataRenderException {
        checkNotNull(exception);

        LOG.debug("Start building Json error document");

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(outputStream, JsonEncoding.UTF8);
            jsonGenerator.writeStartObject();

            jsonGenerator.writeObjectFieldStart(ERROR);

            jsonGenerator.writeStringField(CODE, String.valueOf(exception.getCode().getCode()));
            jsonGenerator.writeStringField(MESSAGE, String.valueOf(exception.getMessage()));
            // optional
            if (exception.getTarget() != null) {
                jsonGenerator.writeStringField(TARGET, String.valueOf(exception.getTarget()).replace("\"", "'"));
            }
            jsonGenerator.writeEndObject();
            jsonGenerator.close();

            return outputStream.toString();
        } catch (IOException e) {
            LOG.error("Not possible to write error JSON.");
            throw new ODataRenderException("Not possible to write error JSON: ", e);
        }
    }
764508
def json_format_dict(self, data, pretty=False):
        '''  '''

        if pretty:
            return json.dumps(data, sort_keys=True, indent=2)
        else:
            return json.dumps(data)
189923
def _get_response_json(self, res):
        

        try:
            error = res.json()
        except ValueError:
            error = {
                "message": "The API did not respond with JSON, but: {0}".format(res.text[:1000]),
                "error_code": "{0}".format(res.status_code)
            }
        return error
973879
def format_exc(limit=None):
    """"""
    try:
        etype, value, tb = sys.exc_info()
        return ''.join(traceback.format_exception(etype, value, tb, limit))
    finally:
        etype = value = tb = None
275420
def format_for_exception
      return "Command execution failed. STDOUT/STDERR suppressed for sensitive resource" if sensitive
      msg = ""
      msg << "#{@terminate_reason}\n" if @terminate_reason
      msg << "---- Begin output of #{command} ----\n"
      msg << "STDOUT: #{stdout.strip}\n"
      msg << "STDERR: #{stderr.strip}\n"
      msg << "---- End output of #{command} ----\n"
      msg << "Ran #{command} returned #{status.exitstatus}" if status
      msg
    end
301912
def json_numpy_loader():
    """"""
    data = request.get_json()
    logger.debug('Received JSON data of length {:,}'.format(len(data)))
    return data
77838
def json_loads(data):
    """"""
    if data is None:
        return ""

    if data == "-":
        return json.load(sys.stdin)
    elif os.path.exists(data):
        with open(data, 'r') as handle:
            return json.load(handle)
    else:
        return json.loads(data)
1306754
def json_data(self):
        """"""
        return {
            "type": self.type,
            "max_size": self.max_size,
            "full": self.full,
            "role": self.role,
        }
510917
def prepare_exception(obj, messages=None, response=None, verbs=None):
    
    # pylint:disable=too-many-branches
    verbs = set(verbs or [])
    known_options = ['method+url']
    if messages is None:
        messages = []
    if isinstance(messages, (text_type, str)):
        messages = [messages]
    assert isinstance(messages, list)
    assert not verbs.difference(known_options)

    data = None
    # a boolean from a failed response is False, though error messages in json should be decoded
    if response is not None and 'json' in response.headers.get('Content-Type', '') and response.text:
        data = json.loads(response.text)
        if data:
            data_0 = data[0]
            if 'errorCode' in data_0:
                subreq = ''
                if 'referenceId' in data_0:
                    subreq = " (in subrequest {!r})".format(data_0['referenceId'])
                messages = [data_0['errorCode'] + subreq] + messages
            if data_0.get('fields'):
                messages.append('FIELDS: {}'.format(data_0['fields']))
            if len(data) > 1:
                messages.append('MORE_ERRORS ({})'.format(len(data)))
    if 'method+url' in verbs:
        method = response.request.method
        url = response.request.url
        if len(url) > 100:
            url = url[:100] + '...'
        data_info = ''
        if (method in ('POST', 'PATCH') and
                (not response.request.body or 'json' not in response.request.headers['content-type'])):
            data_info = ' (without json request data)'
        messages.append('in {} "{}"{}'.format(method, url, data_info))
    separ = '\n    '
    if not PY3:
        messages = [x if isinstance(x, str) else x.encode('utf-8') for x in messages]
    messages = [x.replace('\n', separ) for x in messages]
    message = separ.join(messages)
    if obj:
        obj.data = data
        obj.response = response
        obj.verbs = verbs
    return message
1320332
def json_error_handler(exception):
    
    http_exception = isinstance(exception, exceptions.HTTPException)
    code = exception.code if http_exception else 500

    # log exceptions only (app debug should be off)
    if code == 500:
        current_app.logger.error(exception)

    response = jsonify(dict(message=str(exception)))
    response.status_code = code
    return response