excutils.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2013, Mahmoud Hashemi
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. #
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following
  13. # disclaimer in the documentation and/or other materials provided
  14. # with the distribution.
  15. #
  16. # * The names of the contributors may not be used to endorse or
  17. # promote products derived from this software without specific
  18. # prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. import sys
  32. import traceback
  33. import linecache
  34. from collections import namedtuple
  35. # TODO: last arg or first arg? (last arg makes it harder to *args
  36. # into, but makes it more readable in the default exception
  37. # __repr__ output)
  38. # TODO: Multiexception wrapper
  39. __all__ = ['ExceptionCauseMixin']
  40. class ExceptionCauseMixin(Exception):
  41. """
  42. A mixin class for wrapping an exception in another exception, or
  43. otherwise indicating an exception was caused by another exception.
  44. This is most useful in concurrent or failure-intolerant scenarios,
  45. where just because one operation failed, doesn't mean the remainder
  46. should be aborted, or that it's the appropriate time to raise
  47. exceptions.
  48. This is still a work in progress, but an example use case at the
  49. bottom of this module.
  50. NOTE: when inheriting, you will probably want to put the
  51. ExceptionCauseMixin first. Builtin exceptions are not good about
  52. calling super()
  53. """
  54. cause = None
  55. def __new__(cls, *args, **kw):
  56. cause = None
  57. if args and isinstance(args[0], Exception):
  58. cause, args = args[0], args[1:]
  59. ret = super(ExceptionCauseMixin, cls).__new__(cls, *args, **kw)
  60. ret.cause = cause
  61. if cause is None:
  62. return ret
  63. root_cause = getattr(cause, 'root_cause', None)
  64. if root_cause is None:
  65. ret.root_cause = cause
  66. else:
  67. ret.root_cause = root_cause
  68. full_trace = getattr(cause, 'full_trace', None)
  69. if full_trace is not None:
  70. ret.full_trace = list(full_trace)
  71. ret._tb = list(cause._tb)
  72. ret._stack = list(cause._stack)
  73. return ret
  74. try:
  75. exc_type, exc_value, exc_tb = sys.exc_info()
  76. if exc_type is None and exc_value is None:
  77. return ret
  78. if cause is exc_value or root_cause is exc_value:
  79. # handles when cause is the current exception or when
  80. # there are multiple wraps while handling the original
  81. # exception, but a cause was never provided
  82. ret._tb = _extract_from_tb(exc_tb)
  83. ret._stack = _extract_from_frame(exc_tb.tb_frame)
  84. ret.full_trace = ret._stack[:-1] + ret._tb
  85. finally:
  86. del exc_tb
  87. return ret
  88. def get_str(self):
  89. """
  90. Get formatted the formatted traceback and exception
  91. message. This function exists separately from __str__()
  92. because __str__() is somewhat specialized for the built-in
  93. traceback module's particular usage.
  94. """
  95. ret = []
  96. trace_str = self._get_trace_str()
  97. if trace_str:
  98. ret.extend(['Traceback (most recent call last):\n', trace_str])
  99. ret.append(self._get_exc_str())
  100. return ''.join(ret)
  101. def _get_message(self):
  102. args = getattr(self, 'args', [])
  103. if self.cause:
  104. args = args[1:]
  105. if args and args[0]:
  106. return args[0]
  107. return ''
  108. def _get_trace_str(self):
  109. if not self.cause:
  110. return super(ExceptionCauseMixin, self).__repr__()
  111. if self.full_trace:
  112. return ''.join(traceback.format_list(self.full_trace))
  113. return ''
  114. def _get_exc_str(self, incl_name=True):
  115. cause_str = _format_exc(self.root_cause)
  116. message = self._get_message()
  117. ret = []
  118. if incl_name:
  119. ret = [self.__class__.__name__, ': ']
  120. if message:
  121. ret.extend([message, ' (caused by ', cause_str, ')'])
  122. else:
  123. ret.extend([' caused by ', cause_str])
  124. return ''.join(ret)
  125. def __str__(self):
  126. if not self.cause:
  127. return super(ExceptionCauseMixin, self).__str__()
  128. trace_str = self._get_trace_str()
  129. ret = []
  130. if trace_str:
  131. message = self._get_message()
  132. if message:
  133. ret.extend([message, ' --- '])
  134. ret.extend(['Wrapped traceback (most recent call last):\n',
  135. trace_str,
  136. self._get_exc_str(incl_name=True)])
  137. return ''.join(ret)
  138. else:
  139. return self._get_exc_str(incl_name=False)
  140. def _format_exc(exc, message=None):
  141. if message is None:
  142. message = exc
  143. exc_str = traceback._format_final_exc_line(exc.__class__.__name__, message)
  144. return exc_str.rstrip()
  145. _BaseTBItem = namedtuple('_BaseTBItem', 'filename, lineno, name, line')
  146. class _TBItem(_BaseTBItem):
  147. def __repr__(self):
  148. ret = super(_TBItem, self).__repr__()
  149. ret += ' <%r>' % self.frame_id
  150. return ret
  151. class _DeferredLine(object):
  152. def __init__(self, filename, lineno, module_globals=None):
  153. self.filename = filename
  154. self.lineno = lineno
  155. module_globals = module_globals or {}
  156. self.module_globals = dict([(k, v) for k, v in module_globals.items()
  157. if k in ('__name__', '__loader__')])
  158. def __eq__(self, other):
  159. return (self.lineno, self.filename) == (other.lineno, other.filename)
  160. def __ne__(self, other):
  161. return (self.lineno, self.filename) != (other.lineno, other.filename)
  162. def __str__(self):
  163. if hasattr(self, '_line'):
  164. return self._line
  165. linecache.checkcache(self.filename)
  166. line = linecache.getline(self.filename,
  167. self.lineno,
  168. self.module_globals)
  169. if line:
  170. line = line.strip()
  171. else:
  172. line = None
  173. self._line = line
  174. return line
  175. def __repr__(self):
  176. return repr(str(self))
  177. def __len__(self):
  178. return len(str(self))
  179. def strip(self):
  180. return str(self).strip()
  181. def _extract_from_frame(f=None, limit=None):
  182. ret = []
  183. if f is None:
  184. f = sys._getframe(1) # cross-impl yadayada
  185. if limit is None:
  186. limit = getattr(sys, 'tracebacklimit', 1000)
  187. n = 0
  188. while f is not None and n < limit:
  189. filename = f.f_code.co_filename
  190. lineno = f.f_lineno
  191. name = f.f_code.co_name
  192. line = _DeferredLine(filename, lineno, f.f_globals)
  193. item = _TBItem(filename, lineno, name, line)
  194. item.frame_id = id(f)
  195. ret.append(item)
  196. f = f.f_back
  197. n += 1
  198. ret.reverse()
  199. return ret
  200. def _extract_from_tb(tb, limit=None):
  201. ret = []
  202. if limit is None:
  203. limit = getattr(sys, 'tracebacklimit', 1000)
  204. n = 0
  205. while tb is not None and n < limit:
  206. filename = tb.tb_frame.f_code.co_filename
  207. lineno = tb.tb_lineno
  208. name = tb.tb_frame.f_code.co_name
  209. line = _DeferredLine(filename, lineno, tb.tb_frame.f_globals)
  210. item = _TBItem(filename, lineno, name, line)
  211. item.frame_id = id(tb.tb_frame)
  212. ret.append(item)
  213. tb = tb.tb_next
  214. n += 1
  215. return ret
  216. # An Example/Prototest:
  217. class MathError(ExceptionCauseMixin, ValueError):
  218. pass
  219. def whoops_math():
  220. return 1/0
  221. def math_lol(n=0):
  222. if n < 3:
  223. return math_lol(n=n+1)
  224. try:
  225. return whoops_math()
  226. except ZeroDivisionError as zde:
  227. exc = MathError(zde, 'ya done messed up')
  228. raise exc
  229. def main():
  230. try:
  231. math_lol()
  232. except ValueError as me:
  233. exc = MathError(me, 'hi')
  234. raise exc
  235. if __name__ == '__main__':
  236. try:
  237. main()
  238. except Exception:
  239. import pdb;pdb.post_mortem()
  240. raise