2014-10-07 49 views
0

假设您有一个现有的应用程序,并且想要修改整个应用程序的异常处理。无法将该应用程序包装在begin/rescue区块中。是否有可能在Ruby的init文件中设置异常处理程序?

通过添加在应用程序启动之前运行的代码来修改异常处理程序(以抑制回溯)的好方法是什么?

+0

是我的回答你在找什么? – daremkd 2014-10-13 23:06:07

+1

是的,它非常有用。谢谢。 – 2014-10-14 02:32:52

回答

1

开始/救援不是方法,所以你不能覆盖它们。如果发生异常,则会展开几个步骤,第一个步骤是......在您通过例外的任何对象上调用.exception。例如:

class A 
    def exception 
    p 'I am going to print' 
    RuntimeError.new('message') 
    end 
end 

a = A.new 
raise a #=> 'I am going to print' and then runtime error is raised 

如果你控制你传递给'raise'的东西,那么你可以传递一个对象。调用.raise之后的第一步是调用该对象的.exception方法,正如您从此处可以看到的那样。

如果你不想回溯到终端显示在所有,使用中止而不是加薪:

abort 'aborting!' #=> prints 'aborting' to STDERR and then does exit 1 implicitly. No backtrace is shown. 

你可以用的方法,整个应用程序,将做所有的异常处理你:

def exception_handler 
    puts 'Do whatever you want here before the app starts executing' 
    yield 
rescue 
    # put the logic of handling errors here 
    # for example, you could do 'abort 'error occured'' that will make the program stop and not show a backtrace 
end 

exception_handler do 
    puts 'My app code goes here' 
end 

会打印:

Do whatever you want here before the app starts executing 
My app code goes here 

比方说,你的应用程序提出了一堆参数错误。你可以做的是重新打开课程并在提高之前执行一些代码:

class ArgumentError 
    alias_method :real_initialize, :initialize 
    def initialize(*args) # we're overriding initialize 
    super(*args) 
    p 'some code here' 
    end 
end 

raise ArgumentError 
相关问题