Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import traceback
- import inspect
- import sys
- class MyError(Exception):
- def __init__(self, msg):
- super().__init__(msg)
- upstack, linenum = next(traceback.walk_stack(None))
- self.linenum = linenum
- self.traceback = upstack
- self.msg = msg
- args, _, _, values = inspect.getargvalues(upstack)
- self.func_args = {
- k:values[k] for k in args
- }
- def __str__(self):
- return """
- [ERROR] '{msg}'
- Occured at line: {linenum}
- In file: {filename}
- In function: {funcname} (starts at line {funcline})
- Called with args: {funcargs}
- """.format(
- msg=self.msg,
- linenum=self.linenum,
- filename=self.traceback.f_code.co_filename,
- funcname=self.traceback.f_code.co_name,
- funcline=self.traceback.f_code.co_firstlineno,
- funcargs=str(self.func_args)
- ).strip()
- def foo(yay_arg, foo_arg):
- try:
- raise MyError("Helpful Error Message")
- except MyError as e:
- print(e)
- if __name__ == "__main__":
- foo("one", foo_arg="bar")
- >>>> [ERROR] 'Helpful Error Message'
- >>>> Occured at line: 35
- >>>> In file: custom_exceptions.py
- >>>> In function: foo (starts at line 33)
- >>>> Called with args: {'foo_arg': 'bar', 'yay_arg': 'one'}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement