如果你想走一条不一样的路,尝试这个:
class Exception
alias real_init initialize
def initialize(*args)
real_init *args
# log the error (self) or its args here
end
end
这将拦截在创建时刻新异常对象的创建。
从Exception
中恢复。类似这样的内容可能是有意义的:
begin
# run your code here ..
rescue Exception => exception
# logger.error(...) ....
raise exception
end
这将记录异常,并重新引发它,以便应用程序实际上会在日志记录之外引发错误。
exception
是 Exception
的一个实例,请查看文档以获取有关此对象的信息(例如访问回溯)。
rescue
块中,您可以简单地编写 raise
,据我所知,这是重新引发刚捕获的异常的惯用方式。 - tokland如果我这样做,它会起作用吗:
begin
main()
rescue Exception => e
myCustomErrorLogger(e)
end
def main()
# All the application code comes here.
end
您可以调整 Exception 类的代码,以在将原因和回溯放入标准输出时进行修改。
不要忘记检查记录器是否为空,异常可能会在记录器创建之前(或期间)被抛出。