2010-12-02 7 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

답변

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