Extract a useful error message from the last thrown exception
196235
def _extract_msg_from_last_exception():
    '''  '''
    last_exc_type, last_error, last_traceback = sys.exc_info()
    if isinstance(last_error, exceptions.DXAPIError):
        # Using the same code path as below would not
        # produce a useful message when the error contains a
        # 'details' hash (which would have a last line of
        # '}')
        return last_error.error_message()
    else:
        return traceback.format_exc().splitlines()[-1].strip()
146305
def get_error(self):
        """"""
        col_offset = -1
        if self.node is not None:
            try:
                col_offset = self.node.col_offset
            except AttributeError:
                pass
        try:
            exc_name = self.exc.__name__
        except AttributeError:
            exc_name = str(self.exc)
        if exc_name in (None, 'None'):
            exc_name = 'UnknownError'

        out = ["   %s" % self.expr]
        if col_offset > 0:
            out.append("    %s^^^" % ((col_offset)*' '))
        out.append(str(self.msg))
        return (exc_name, '\n'.join(out))
426632
def ErrorMsg():
    
    import traceback

    limit = None
    _type, value, tb = sys.exc_info()
    _list = traceback.format_tb(tb, limit) + \
        traceback.format_exception_only(_type, value)
    return "Traceback (innermost last):\n" + "%-20s %s" % (
        " ".join(_list[:-1]),
        _list[-1])
475558
def __get_exception_message(self):
        
        exception_info = sys.exc_info()[1]
        if hasattr(exception_info, 'msg'):
            exc_message = exception_info.msg
        elif hasattr(exception_info, 'message'):
            exc_message = exception_info.message
        else:
            exc_message = '(Unknown Exception)'
        return exc_message
99096
private int handleError(Throwable t) {
		System.out.println("Error: " + t.getMessage());
		if (this.verbose) {
			t.printStackTrace();
		} else {
			System.out.println("For a more detailed error message use the vebose output option '-v'.");
		}
		return 1;
	}
856867
public String getLastError(int iErrorCode)
    {
        if ((m_strLastError == null) || ((iErrorCode != 0) && (iErrorCode != m_iLastErrorCode)))
            return Constants.BLANK;
        String string = m_strLastError;
        m_strLastError = null;
        return string;
    }
210001
def errno_from_exception(self, ex):
        
        if hasattr(ex, 'errno'):
            return ex.errno
        elif ex.args:
            return ex.args[0]
        else:
            return None
576528
public static String getExceptionMessage(List throwables)
    {
        if (throwables == null)
        {
            return null;
        }

        for (int i = throwables.size()-1; i>0; i--)
        {
            Throwable t = (Throwable) throwables.get(i);
            if (t.getMessage() != null)
            {
                return t.getMessage();
            }
        }
        
        return null;
    }
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)
291579
def get_last_error(self):
        
        error = ctypes.c_int32()
        result = self.library.Par_GetLastError(self.pointer, ctypes.byref(error))
        check_error(result, "partner")
        return error
1049396
def template_exception_handler(fn, error_context, filename=None):
    """"""
    error_message = None
    if filename:
        error_context.update(filename=filename)
    try:
        return fn()
    except jinja2.TemplateSyntaxError as exc:
        error_context.update(filename=exc.filename, line_no=exc.lineno)
        error_message = exc.message
    except jinja2.TemplateError as exc:
        error_message = exc.message
    except Exception as exc:
        error_message = "%s" % exc

    raise TemplateError(message=error_message, context=error_context)
1221342
def _store_lasterr(self):
        """"""
        from sys import exc_info
        from traceback import format_exception
        e = exc_info()
        self.lasterr = '\n'.join(format_exception(e[0], e[1], e[2]))
1343962
def exceptionCaught(self, exc=None, **kwargs):
        ''
        if isinstance(exc, ExpectedException):  # already reported, don't log
            return
        self.lastErrors.append(stacktrace())
        if kwargs.get('status', True):
            status(self.lastErrors[-1][-1], priority=2)  # last line of latest error
        if options.debug:
            raise
975995
private Exception updateErrorMsg(StringBuilder pErrors, Exception exp) {
        pErrors.append(exp.getClass()).append(": ").append(exp.getMessage()).append("\n");
        return exp;
    }
5034
def exceptionToString(e,silent=False):
    """"""
    exc_type, exc_obj, exc_tb = sys.exc_info()
    s=("\n"+"="*50+"\n")
    s+="EXCEPTION THROWN UNEXPECTEDLY\n"
    s+="  FILE: %s\n"%os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    s+="  LINE: %s\n"%exc_tb.tb_lineno
    s+="  TYPE: %s\n"%exc_type
    s+='-'*50+'\n'
    s+=traceback.format_exc()
    s=s.strip()+'\n'+"="*50+"\n"
    if not silent:
        print(s)
    return s
1086038
def from_validation_exception(cls, exception, **kwargs):
        """"""
        errors = []

        def flatten(error, path=""):
            if isinstance(error, halogen.exceptions.ValidationError):
                if not path.endswith("/"):
                    path += "/"
                if error.attr is not None:
                    path += error.attr
                elif error.index is not None:
                    path += six.text_type(error.index)

                for e in error.errors:
                    flatten(e, path)
            else:
                message = error
                if isinstance(error, Exception):
                    try:
                        message = error.message
                    except AttributeError:
                        message = six.text_type(error)
                # TODO: i18n
                errors.append(Error(message=message, path=path))

        flatten(exception)
        message = kwargs.pop("message", "Validation error.")
        return cls(message=message, errors=sorted(errors, key=lambda error: error.path or ""), **kwargs)
819439
def recover_info_from_exception(err: Exception) -> Dict:
    
    if len(err.args) < 1:
        return {}
    info = err.args[-1]
    if not isinstance(info, dict):
        return {}
    return info