Prepare excetion params or only an exception message

    parameters:
        messages: list of strings, that will be separated by new line
        response: response from a request to SFDC REST API
        verbs: list of options about verbosity
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
285959
def create_exception_for_response(
            cls,
            response_code,
            messages,
            response_id
    ):
        

        error_message = cls._generate_message_error(
            response_code,
            messages,
            response_id
        )

        if response_code == cls._HTTP_RESPONSE_CODE_BAD_REQUEST:
            return BadRequestException(
                error_message,
                response_code,
                response_id
            )
        if response_code == cls._HTTP_RESPONSE_CODE_UNAUTHORIZED:
            return UnauthorizedException(
                error_message,
                response_code,
                response_id
            )
        if response_code == cls._HTTP_RESPONSE_CODE_FORBIDDEN:
            return ForbiddenException(
                error_message,
                response_code,
                response_id
            )
        if response_code == cls._HTTP_RESPONSE_CODE_NOT_FOUND:
            return NotFoundException(
                error_message,
                response_code,
                response_id
            )
        if response_code == cls._HTTP_RESPONSE_CODE_METHOD_NOT_ALLOWED:
            return MethodNotAllowedException(
                error_message,
                response_code,
                response_id
            )
        if response_code == cls._HTTP_RESPONSE_CODE_TOO_MANY_REQUESTS:
            return TooManyRequestsException(
                error_message,
                response_code,
                response_id
            )
        if response_code == cls._HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR:
            return PleaseContactBunqException(
                error_message,
                response_code,
                response_id
            )

        return UnknownApiErrorException(
            error_message,
            response_code,
            response_id
        )
428076
def _process_message(self, msg):
        
        self._logger.info(
            'Processing Message(topic={}, partition={}, offset={}) ...'
            .format(msg.topic, msg.partition, msg.offset))
        try:
            job = self._deserializer(msg.value)
            job_repr = get_call_repr(job.func, *job.args, **job.kwargs)

        except Exception as err:
            self._logger.exception('Job was invalid: {}'.format(err))
            self._execute_callback('invalid', msg, None, None, None, None)
        else:
            self._logger.info('Executing job {}: {}'.format(job.id, job_repr))

            if job.timeout:
                timer = threading.Timer(job.timeout, _thread.interrupt_main)
                timer.start()
            else:
                timer = None
            try:
                res = job.func(*job.args, **job.kwargs)
            except KeyboardInterrupt:
                self._logger.error(
                    'Job {} timed out or was interrupted'.format(job.id))
                self._execute_callback('timeout', msg, job, None, None, None)
            except Exception as err:
                self._logger.exception(
                    'Job {} raised an exception:'.format(job.id))
                tb = traceback.format_exc()
                self._execute_callback('failure', msg, job, None, err, tb)
            else:
                self._logger.info('Job {} returned: {}'.format(job.id, res))
                self._execute_callback('success', msg, job, res, None, None)
            finally:
                if timer is not None:
                    timer.cancel()
960846
private void initMessage(HttpMessage message) {
        StaticMessageContentBuilder staticMessageContentBuilder = StaticMessageContentBuilder.withMessage(message);
        staticMessageContentBuilder.setMessageHeaders(message.getHeaders());
        getAction().setMessageBuilder(new HttpMessageContentBuilder(message, staticMessageContentBuilder));
    }
219446
def _process_inbox_message(self, message: praw.models.Message):
        
        self._func_message(message, *self._func_message_args)
448870
def gotMessage(self, message_id, message):
        
        d = defer.maybeDeferred(self._handle_message, message)
        d.addCallback(self.generate_response)
        d.addCallback(lambda resp: self.reply(message_id, resp))
        return d
1126422
def _process_response(self, request, response):
        
        if request.is_ajax() and hasattr(request, 'horizon'):
            queued_msgs = request.horizon['async_messages']
            if type(response) == http.HttpResponseRedirect:
                # Drop our messages back into the session as per usual so they
                # don't disappear during the redirect. Not that we explicitly
                # use django's messages methods here.
                for tag, message, extra_tags in queued_msgs:
                    getattr(django_messages, tag)(request, message, extra_tags)
                if response['location'].startswith(settings.LOGOUT_URL):
                    redirect_response = http.HttpResponse(status=401)
                    # This header is used for handling the logout in JS
                    redirect_response['logout'] = True
                    if self.logout_reason is not None:
                        utils.add_logout_reason(
                            request, redirect_response, self.logout_reason,
                            'error')
                else:
                    redirect_response = http.HttpResponse()
                # Use a set while checking if we want a cookie's attributes
                # copied
                cookie_keys = {'max_age', 'expires', 'path', 'domain',
                               'secure', 'httponly', 'logout_reason'}
                # Copy cookies from HttpResponseRedirect towards HttpResponse
                for cookie_name, cookie in response.cookies.items():
                    cookie_kwargs = dict((
                        (key, value) for key, value in cookie.items()
                        if key in cookie_keys and value
                    ))
                    redirect_response.set_cookie(
                        cookie_name, cookie.value, **cookie_kwargs)
                redirect_response['X-Horizon-Location'] = response['location']
                upload_url_key = 'X-File-Upload-URL'
                if upload_url_key in response:
                    self._copy_headers(response, redirect_response,
                                       (upload_url_key, 'X-Auth-Token'))
                return redirect_response
            if queued_msgs:
                # TODO(gabriel): When we have an async connection to the
                # client (e.g. websockets) this should be pushed to the
                # socket queue rather than being sent via a header.
                # The header method has notable drawbacks (length limits,
                # etc.) and is not meant as a long-term solution.
                response['X-Horizon-Messages'] = json.dumps(queued_msgs)
        return response
1049328
def build_message(self):
        
        if self.params is None:
            inline_params = ""
        else:
            # Put all params in one string
            inline_params = ""
            if type(self.params) is list:
                for x in self.params:
                    if x != self.params[0]:
                        inline_params += ", "
                    if type(x) is int:
                        inline_params += str(x)
                    else:
                        inline_params += '"{}"'.format(x)
            else:
                inline_params += '"{}"'.format(self.params)

        # Build message with that string
        self.message = self.COMMAND_BODY.format(str(self.command_id), self.method, inline_params)
895288
def exception_message(self) -> Union[str, None]:
        
        if self.has_error:
            exception_data = self._raw.get("exception", {})
            return exception_data.get("message")
        return None
517748
def _message_to_payload(cls, message):
        ''''''
        try:
            return json.loads(message.decode())
        except UnicodeDecodeError:
            message = 'messages must be encoded in UTF-8'
        except json.JSONDecodeError:
            message = 'invalid JSON'
        raise cls._error(cls.PARSE_ERROR, message, True, None)
1226105
public static Response getStatusResponse(Response.Status status, String... messages) {
		if (status == null) {
			return Response.status(Response.Status.BAD_REQUEST).build();
		}
		String msg = StringUtils.join(messages, ". ");
		if (StringUtils.isBlank(msg)) {
			msg = status.getReasonPhrase();
		}
		try {
			return GenericExceptionMapper.getExceptionResponse(status.getStatusCode(), msg);
		} catch (Exception ex) {
			logger.error(null, ex);
			return Response.status(Response.Status.BAD_REQUEST).build();
		}
	}
1072663
protected String formatMessage(String message, Object[] parameters) {
        String formatted;
        if (printfStyle) {
            formatted = String.format(message, parameters);
        } else {
            formatted = MessageFormat.format(message, parameters);
        }
        return formatted;
    }
514068
def _generate_message_error(cls, response_code, messages, response_id):
        

        line_response_code = cls._FORMAT_RESPONSE_CODE_LINE \
            .format(response_code)
        line_response_id = cls._FORMAT_RESPONSE_ID_LINE.format(response_id)
        line_error_message = cls._FORMAT_ERROR_MESSAGE_LINE.format(
            cls._GLUE_ERROR_MESSAGE_STRING_EMPTY.join(messages)
        )

        return cls._glue_all_error_message(
            [line_response_code, line_response_id, line_error_message]
        )
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)
759800
def got_message message
      @client.got_message self, message
    rescue StandardError => exception
      puts "#{exception.class}: #{exception.message}"
      puts
      puts '---'
      puts exception.backtrace
    end
773803
private String format(String message, Object[] params) {
        if (params.length == 0) {
            return message;
        } else if (params.length == 1 && params[0] instanceof Throwable) {
            // We print only the message here since breaking exception will bubble up
            // anyway
            return message + ": " + params[0].toString();
        } else {
            return String.format(message, params);
        }
    }
440376
def expected_error_messages(*error_messages):
    
    def wrapper(func):
        setattr(func, EXPECTED_ERROR_MESSAGES, error_messages)
        return func
    return wrapper