Skip to content

Instantly share code, notes, and snippets.

@chuanwang66
Created October 31, 2014 03:26
Show Gist options
  • Save chuanwang66/28cda27fa1fd20560564 to your computer and use it in GitHub Desktop.
Save chuanwang66/28cda27fa1fd20560564 to your computer and use it in GitHub Desktop.
common/TryExceptWrapper:
import inspect
import sys
class MyException(Exception):
pass
def show_stack(stack):
stack_len = len(stack)
assert stack_len >= 2
stack_info = ""
for i in xrange(0, stack_len):
caller_frame_record = stack[i]
caller_frame = caller_frame_record[0]
caller_info = inspect.getframeinfo(caller_frame)
stack_info += "frame %d: file[%s], func[%s], line[%s]\n"%(i, caller_info.filename, caller_info.function, caller_info.lineno)
LOG.error(stack_info)
def try_except(fn):
"""
@try_except is adopted to record exceptions all the time
"""
def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except Exception, e:
et, ei, tb = sys.exc_info()
LOG.error("%s\n%s"%(et, ei))
#show stack frames from the caller
stack = inspect.stack()
show_stack(stack)
raise MyException, MyException(e), tb
return wrapped
使用:
from common.TryExceptWrapper import try_except
在任意def fun()方法上面加上
@try_except
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment