Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save harshithjv/c48442cc8d49e56712174998bb6142eb to your computer and use it in GitHub Desktop.

Select an option

Save harshithjv/c48442cc8d49e56712174998bb6142eb to your computer and use it in GitHub Desktop.

Keeping this stackoverflow answer(Python) handy for future use:

try:
    func1()
except Exception as ex:
    trace = []
    tb = ex.__traceback__
    while tb is not None:
        trace.append({
            "filename": tb.tb_frame.f_code.co_filename,
            "name": tb.tb_frame.f_code.co_name,
            "lineno": tb.tb_lineno
        })
        tb = tb.tb_next
    print(str({
        'type': type(ex).__name__,
        'message': str(ex),
        'trace': trace
    }))

Output:

{
  "type": "ZeroDivisionError",
  "message": "division by zero",
  "trace": [
    {
      "filename": "/var/playground/main.py",
      "name": "<module>",
      "lineno": 16
    },
    {
      "filename": "/var/playground/main.py",
      "name": "func1",
      "lineno": 11
    },
    {
      "filename": "/var/playground/main.py",
      "name": "func2",
      "lineno": 7
    },
    {
      "filename": "/var/playground/my.py",
      "name": "test",
      "lineno": 2
    }
  ]
}

StackOverflow link: https://stackoverflow.com/a/64212552

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment