0
假設您有一個現有的應用程序,並且想要修改整個應用程序的異常處理。無法將該應用程序包裝在begin/rescue
區塊中。是否有可能在Ruby的init文件中設置異常處理程序?
通過添加在應用程序啓動之前運行的代碼來修改異常處理程序(以抑制回溯)的好方法是什麼?
假設您有一個現有的應用程序,並且想要修改整個應用程序的異常處理。無法將該應用程序包裝在begin/rescue
區塊中。是否有可能在Ruby的init文件中設置異常處理程序?
通過添加在應用程序啓動之前運行的代碼來修改異常處理程序(以抑制回溯)的好方法是什麼?
開始/救援不是方法,所以你不能覆蓋它們。如果發生異常,則會展開幾個步驟,第一個步驟是......在您通過例外的任何對象上調用.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
是我的回答你在找什麼? – daremkd 2014-10-13 23:06:07
是的,它非常有用。謝謝。 – 2014-10-14 02:32:52