Look for additional error strings in the response and return formatted exception
559545
private function _reportAnyErrors($responseBody, $status, $responseHeaderMetadata, Exception $e =  null)
    {
        $exProps = array();
        $exProps["StatusCode"] = $status;
        $exProps["ResponseHeaderMetadata"] = $responseHeaderMetadata;

        libxml_use_internal_errors(true);  // Silence XML parsing errors
        $xmlBody = simplexml_load_string($responseBody);

        if ($xmlBody !== false) {  // Check XML loaded without errors
            $exProps["XML"] = $responseBody;
            $exProps["ErrorCode"] = $xmlBody->Error->Code;
            $exProps["Message"] = $xmlBody->Error->Message;
            $exProps["ErrorType"] = !empty($xmlBody->Error->Type) ? $xmlBody->Error->Type : "Unknown";
            $exProps["RequestId"] = !empty($xmlBody->RequestID) ? $xmlBody->RequestID : $xmlBody->RequestId; // 'd' in RequestId is sometimes capitalized
        } else { // We got bad XML in response, just throw a generic exception
            $exProps["Message"] = "Internal Error";
        }

        require_once (dirname(__FILE__) . '/Exception.php');
        return new MarketplaceWebServiceProducts_Exception($exProps);
    }
935662
def from_response(response):
        '''
        
        '''
        cls = PLAID_ERROR_TYPE_MAP.get(response['error_type'], PlaidError)
        return cls(response['error_message'],
                   response['error_type'],
                   response['error_code'],
                   response['display_message'],
                   response['request_id'],
                   response.get('causes'))
452040
def error_response(self, exception):
        # type: (Exception) -> Tuple[Callback, Error]
        """"""
        response = Error(id=self.id, message=exception)
        log.exception("Exception raised for request %s", self)
        return self.callback, 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
442512
def _get_error_response(self, exception):
        
        response_exceptions = {
            MimerDataException: HTTPBadRequestResponseException,
            NotAllowedException: HTTPForbiddenResponseException,
            UnsupportedMediaTypeException: HTTPUnsupportedMediaTypeResponseException,
            Http404: Http404,
            ResourceNotFoundException: Http404,
            NotAllowedMethodException: HTTPMethodNotAllowedResponseException,
            DuplicateEntryException: HTTPDuplicateResponseException,
            ConflictException: HTTPDuplicateResponseException,
        }
        response_exception = response_exceptions.get(type(exception))
        if response_exception:
            raise response_exception
        return super(RESTResourceMixin, self)._get_error_response(exception)
6770
def get_exception_error():
        ''' 
        '''
        error_message = ""
        for i in range(len(inspect.trace())):
            error_line = u"""
        File:      %s - [%s]
        Function:  %s
        Statement: %s
        -""" % (inspect.trace()[i][1], inspect.trace()[i][2], inspect.trace()[i][3], inspect.trace()[i][4])
            
            error_message = "%s%s" % (error_message, error_line)    
        
        error_message = u"""Error!\n%s\n\t%s\n\t%s\n-------------------------------------------------------------------------------------------\n\n""" % (error_message,sys.exc_info()[0], sys.exc_info()[1])
        
        return error_message
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
278979
def from_response(response, url):
    
    # noinspection PyBroadException
    try:
        data = response.json()
        if not isinstance(data, dict):
            return from_status(
                response.status_code, response.text,
                extra=dict(url=url, response=response.text)
            )

        code = data.get('code', response.status_code)
        if code in HTTP_STATUS_CODES:
            return HTTP_STATUS_CODES[code](**ErrorSchema().load(data))
        else:
            return Error(**ErrorSchema().load(data))
    except Exception:
        return from_status(
            response.status_code, response.text,
            extra=dict(url=url, response=response.text)
        )
1280410
def formatException(self, exc_info, record=None):
        """"""
        if not record:
            return logging.Formatter.formatException(self, exc_info)

        stringbuffer = cStringIO.StringIO()
        traceback.print_exception(exc_info[0], exc_info[1], exc_info[2],
                                  None, stringbuffer)
        lines = stringbuffer.getvalue().split('\n')
        stringbuffer.close()

        if CONF.logging_exception_prefix.find('%(asctime)') != -1:
            record.asctime = self.formatTime(record, self.datefmt)

        formatted_lines = []
        for line in lines:
            pl = CONF.logging_exception_prefix % record.__dict__
            fl = '%s%s' % (pl, line)
            formatted_lines.append(fl)
        return '\n'.join(formatted_lines)
772063
function hasException()
    {
        // Check exception from raw response
        // Server Response Status is 200 but Logical Error May Happen And Returned in Response Body
        if (! $this->exception ) {
            $res = $this->expected();
            if ($res instanceof DataEntity) {
                // Response Body Can parsed To Data Structure
                if ( $exception = $res->get('error') ) {
                    // TODO handle token revoke exceptions; OAuth Exceptions
                    $this->exception = new exTokenMismatch(
                        $res->get('error_description')
                        .' '
                        .$res->get('hint')

                        , 401
                    );
                }
            }
        } else if ($this->exception instanceof exHttpResponse) {
            // Determine Known Errors ...
            $expected = $this->expected();
            if ($expected && $err = $expected->get('error') ) {

                if ( is_string($err) )
                {
                    switch ($err) {
                        case 'access_denied':
                        case 'invalid_grant':
                            $description = $expected->get('error_description');
                            $this->exception = new exOAuthAccessDenied($description);
                            break;
                        case 'invalid_request':
                            $description = $expected->get('error_description');
                            $this->exception = new exInvalidRequest($description);
                            break;
                    }

                } elseif (isset($err['state']))
                {
                    switch (@$err['state']) {
                        case 'exUserNotFound':
                            $this->exception = new exUserNotFound($err['message'], (int)$err['code']);
                            break;
                        case 'exOAuthAccessDenied':
                            $this->exception = new exTokenMismatch($err['message'], (int)$err['code']);
                            break;
                        case 'exIdentifierExists':
                            $this->exception = new exIdentifierExists($err['message'], (int)$err['code']);
                            break;
                        case 'exPasswordNotMatch':
                            $this->exception = new exPasswordNotMatch($err['message'], (int)$err['code']);
                            break;
                        case 'exUnexpectedValue':
                            $this->exception = new exUnexpectedValue($err['message'], (int)$err['code']);
                            break;
                        case 'exMessageMalformed':
                            $this->exception = new exUnexpectedValue($err['message'], (int)$err['code']);
                            break;
                    }
                }
            }
        }


        return $this->exception;
    }
550911
function formatError(e) {
    if (!e.err) {
        return e.message
    }
    // PluginError
    if (typeof e.err.showStack === 'boolean') {
        return e.err.toString()
    }
    // Normal error
    if (e.err.stack) {
        return e.err.stack
    }
    // Unknown (string, number, etc.)
    return new Error(String(e.err)).stack
}
59166
function checkResponseForErrors(res) {
    let { statusCode, body, headers } = res;

    if (statusCode >= 400) {
        return { error: true, body };
    }

    // API key is invalid
    if ((body.error) && (body.error === 'Unauthorized')) {
        return { error: true, body };
    }

    // response is not json
    if (headers['content-type'] !== 'application/json; charset=utf-8') {
        return { error: true, body: { error: 'JSON expected' } };
    }

    return { error: false, body };
}
1059032
function formatError(e) {
  if (!e.err) return e.message;
  if (e.err.message) return e.err.message;
  return JSON.stringify(e.err);
}
1162278
def _get_error(self, code, errors, indentation=0):
        
        # Init
        results = []
        lines = None
        if code is not None:
            lines = [line.strip() for line in code.split('\n')]

        for error in errors.split('\n'):
            # Strip; skip empy lines
            error = error.strip()
            if not error:
                continue
            # Separate line number from description (if we can)
            linenr, error = self._parse_error(error)
            if None in (linenr, lines):
                results.append('%s' % error)
            else:
                results.append('on line %i: %s' % (linenr, error))
                if linenr > 0 and linenr < len(lines):
                    results.append('  %s' % lines[linenr - 1])

        # Add indentation and return
        results = [' ' * indentation + r for r in results]
        return '\n'.join(results)
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)
268212
def _check_for_errors(response, json_response):
        
        status_code = response.status_code
        try:
            response.raise_for_status()
        except requests.HTTPError as why:
            raise ApiError(str(why), reply_code=status_code)
        if isinstance(json_response, dict) and 'error' in json_response:
            raise ApiError(json_response['error'], reply_code=status_code)
441377
def handle_api_exceptions(
    ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False
):
    """"""
    # flake8: ignore=C901
    # Use stderr for messages if the output is something else (e.g.  # JSON)
    use_stderr = opts.output != "pretty"

    try:
        yield
    except ApiException as exc:
        if nl:
            click.echo(err=use_stderr)
            click.secho("ERROR: ", fg="red", nl=False, err=use_stderr)
        else:
            click.secho("ERROR", fg="red", err=use_stderr)

        context_msg = context_msg or "Failed to perform operation!"
        click.secho(
            "%(context)s (status: %(code)s - %(code_text)s)"
            % {
                "context": context_msg,
                "code": exc.status,
                "code_text": exc.status_description,
            },
            fg="red",
            err=use_stderr,
        )

        detail, fields = get_details(exc)
        if detail or fields:
            click.echo(err=use_stderr)

            if detail:
                click.secho(
                    "Detail: %(detail)s"
                    % {"detail": click.style(detail, fg="red", bold=False)},
                    bold=True,
                    err=use_stderr,
                )

            if fields:
                for k, v in six.iteritems(fields):
                    field = "%s Field" % k.capitalize()
                    click.secho(
                        "%(field)s: %(message)s"
                        % {
                            "field": click.style(field, bold=True),
                            "message": click.style(v, fg="red"),
                        },
                        err=use_stderr,
                    )

        hint = get_error_hint(ctx, opts, exc)
        if hint:
            click.echo(
                "Hint: %(hint)s" % {"hint": click.style(hint, fg="yellow")},
                err=use_stderr,
            )

        if opts.verbose and not opts.debug:
            if exc.headers:
                click.echo(err=use_stderr)
                click.echo("Headers in Reply:", err=use_stderr)
                for k, v in six.iteritems(exc.headers):
                    click.echo(
                        "%(key)s = %(value)s" % {"key": k, "value": v}, err=use_stderr
                    )

        if reraise_on_error:
            six.reraise(*sys.exc_info())

        if exit_on_error:
            ctx.exit(exc.status or 1)