Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

proper way to get nice string from exception

I want to generate a one-line string from an Exception which tells me what happened where (don't need a full backtrace). The following information would be nice:

  • filename / linenumber
  • exception type
  • exception description (what you get from str(e))
  • nice to have: function/method/class

Currently I do the following:

import os
...
try:
    os.nonexisting()
except Exception as e:
    t = e.__traceback__
    tbf = e.__traceback__.tb_frame
    print('%s:%d: %s in %s(): "%s" ' %
        os.path.basename(tbf.f_code.co_filename),
        t.tb_lineno,
        e.__class__.__name__,
        tbf.f_code.co_name, e))

which gives me:

foo.py:203: AttributeError in foo(): "'module' object has no attribute 'nonexisting'"

Is there a more elegant way to print out the details given in this example? I'm thinking about s.th. like

print(e.format('%f: %l: %t %F: "%w"'))

I'd like to avoid importing extra modules except there is one exactly for this purpose.

like image 584
frans Avatar asked Sep 27 '22 16:09

frans


1 Answers

I think traceback.format_exception_only does exactly what you want.

try:
    os.nonexisting()
except Exception as e:
    print(traceback.format_exception_only(e.__class__, e))
like image 106
Daniel Roseman Avatar answered Oct 07 '22 19:10

Daniel Roseman