Skip to content

Instantly share code, notes, and snippets.

@KasRoudra
Last active May 22, 2022 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KasRoudra/77e3c39829004540c2f205709288730e to your computer and use it in GitHub Desktop.
Save KasRoudra/77e3c39829004540c2f205709288730e to your computer and use it in GitHub Desktop.
Exception handler for both python2 and python3
from sys import exc_info, version_info
from os.path import abspath
blue = "\033[0;34m"
white ="\033[0;37m"
red = "\033[0;31m"
error = "{}[{}!{}] {}".format(blue, white, blue, red)
def exception_handler(e, multiline=False):
lines_arr = []
exc_type, exc_value, exc_traceback = exc_info()
if version_info[0] == 3:
tb = e.__traceback__
filename = abspath(__file__)
if version_info[0] == 2:
tb = exc_traceback
filename = __file__
while tb is not None:
if tb.tb_frame.f_code.co_filename == filename:
lines_arr.append(str(tb.tb_lineno))
tb = tb.tb_next
name = type(e).__name__
if str(e).find(":")!=-1:
message = str(e).split(":")[0]
elif str(e).find("(")!=-1:
message = str(e).split("(")[0]
else:
message = str(e)
line_no = lines_arr[len(lines_arr) - 1]
lines_no = ", ".join(lines_arr)
if multiline:
print("{}{}: {} at lines {}".format(error, name, message, lines_no))
else:
print("{}{}: {} at line {}".format(error, name, message, line_no))
exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment