Rails on me :)
2010년 3월 26일 금요일
  Ruby on Rails : Action Controller 예외처리(404, 500) 다루기
사용자가 브라우저에 존재하지 않는 경로를 요청하거나, 혹은 잘못된 ID값을 get 방식으로 전달할 때 Rails 는 exception 을 일으킨다. Rails API의 ActionController::Rescue 모듈에 관한 설명에는 다음과 같이 나와있다.

Actions that fail to perform as expected throw exceptions. These exceptions can either be rescued for the public view (with a nice user-friendly explanation) or for the developers view (with tons of debugging information). The developers view is already implemented by the Action Controller, but the public view should be tailored to your specific application.

The default behavior for public exceptions is to render a static html file with the name of the error code thrown. If no such file exists, an empty response is sent with the correct status code.

You can override what constitutes a local request by overriding the local_request? method in your own controller. Custom rescue behavior is achieved by overriding the rescue_action_in_public and rescue_action_locally methods.

위의 설명대로, rescue_action_in_public 와 rescue_action_locally 함수를 오버라이딩 함으로써 잘못수행된 요청에 대한 처리를 할수 있다.
rescue_action 메서드 명뒤에 붙은 public 과 local 은 어떤 차이가 있을까? 잘못된 수행에 의해 exception 이 발생할때, Rails 는 local_request? 함수를 통해 먼저 이 exception이 localhost 에서 발생했는지를 체크한다. 만약, true 일 경우, rescue_action_locally 를 호출하며 rescue_action_public 은 호출하지 않는다.

위의 exception 발생환경에 따른 분기는 유용할지도 모르나, 내 경우 모든 경우가 localhost 에서 발생했기에, rescue_action_in_public 을 언제 활용할 수 있는지는 모르겠다. 아래의 예제는 두 환경을 동일하게 처리하도록 코딩된 예제이다.
ApplicationController 에 다음 메서드를 오버라이딩 한다.


def rescue_action_in_public(exception)
  case exception
    when ActiveRecord::RecordNotFound, ActionController::RoutingError, ActionController::UnknownController, ActionController::UnknownAction
      #render_404
      render :file => "#{RAILS_ROOT}/public/404.html", :layout => false, :status => 404
    else
      #render_500
      render :file => "#{RAILS_ROOT}/public/500.html", :layout => false, :status => 500
    end
end

def rescue_action_locally(exception)
  rescue_action_in_public(exception)
end

라벨: , , , ,

 
댓글: 댓글 쓰기

에 가입 댓글 [Atom]





<< 홈
with ruby core and CGIs

내 사진
이름:
위치: Seoul, South Korea

모니터 앞에서 싸구려 커피를 마시며

아카이브
3월 2010 / 4월 2010 / 5월 2010 / 6월 2010 / 7월 2010 / 11월 2010 / 12월 2011 /


Powered by Blogger

에 가입
글 [Atom]