Advertisement
Guest User

Untitled

a guest
May 4th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. import traceback
  2. import inspect
  3. import sys
  4.  
  5. class MyError(Exception):
  6. def __init__(self, msg):
  7. super().__init__(msg)
  8. upstack, linenum = next(traceback.walk_stack(None))
  9. self.linenum = linenum
  10. self.traceback = upstack
  11. self.msg = msg
  12. args, _, _, values = inspect.getargvalues(upstack)
  13. self.func_args = {
  14. k:values[k] for k in args
  15. }
  16.  
  17. def __str__(self):
  18. return """
  19. [ERROR] '{msg}'
  20. Occured at line: {linenum}
  21. In file: {filename}
  22. In function: {funcname} (starts at line {funcline})
  23. Called with args: {funcargs}
  24. """.format(
  25. msg=self.msg,
  26. linenum=self.linenum,
  27. filename=self.traceback.f_code.co_filename,
  28. funcname=self.traceback.f_code.co_name,
  29. funcline=self.traceback.f_code.co_firstlineno,
  30. funcargs=str(self.func_args)
  31. ).strip()
  32.  
  33. def foo(yay_arg, foo_arg):
  34. try:
  35. raise MyError("Helpful Error Message")
  36. except MyError as e:
  37. print(e)
  38.  
  39.  
  40. if __name__ == "__main__":
  41. foo("one", foo_arg="bar")
  42.  
  43. >>>> [ERROR] 'Helpful Error Message'
  44. >>>> Occured at line: 35
  45. >>>> In file: custom_exceptions.py
  46. >>>> In function: foo (starts at line 33)
  47. >>>> Called with args: {'foo_arg': 'bar', 'yay_arg': 'one'}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement