2010-12-02 150 views
4

我有一系列使用相同異常處理的方法。抽象異常檢查

如何將異常檢查抽象爲單獨的函數?

查看下面的示例,非常感謝您的幫助人員!

def a 
    code 
    begin 
    rescue 1... 
    rescue 2... 
    rescue 3... 
    rescue 4... 
    end 
end 

def b 
    code 
    begin 
    rescue 1... 
    rescue 2... 
    rescue 3... 
    rescue 4... 
    end 
end 
+0

這是模型,控制器或其他? – hade 2010-12-02 10:51:28

回答

10

最簡單的解決辦法是將你的代碼傳遞給方法的塊和開始/救援表達式中屈服於它:

def run_code_and_handle_exceptions 
    begin 
    yield 
    rescue 1... 
    rescue 2... 
    rescue 3... 
    rescue 4... 
    end 
end 

# Elsewhere... 
def a 
    run_code_and_handle_exceptions do 
    code 
    end 
end 
# etc... 

您可能要拿出一個更簡潔方法名稱比run_code_and_handle_exceptions!

1

在控制器中我使用了rescue_from -functionality。這是相當幹:

class HelloWorldController < ApplicationController 
    rescue_from ActiveRecord::RecordNotFound, :with => :handle_unfound_record 

    def handle_unfound_record 
    # Exception handling... 
    end