레일스에서 예외 처리 활용하기 - RescueException 플러그인
November 6th, 2007
예외(Exception)를 발생시키는 부분과 이를 처리하는 부분을 분리해서 DRY를 추구하고 있었다. 레일즈 애플리케이션의 가장 널리 쓰이는 에러처리 방법은 크게 2개다. render 하거나, redirect 하거나. 그래서 ApplicationController에서 no_permission이라는 메서드를 만들고 예외 상황에 이를 호출했다.
- class TestController
- def sample
- return no_permission unless can_do_something?
- do_some_thing
- end
- def no_permission
- #ApplicationHandler의 것을 재정의
- render :text => '403 Forbidden', :status => "403 Forbidden"
- end
- end
그러다가 '루비에 예외처리 개념이 이미 있는데, 왜 이를 사용하지 않지?'라는 의문이 들었다. 그래서 한번 만들어보았다.
예외 처리
코드가 많은 부분을 이야기해주리라 생각한다. 위의 코드를 바꾸면 이런 식이다.
- class NoPermission < ::ActionController::ActionControllerError; end
class ApplicationController < ActionController::Base
rescue_exception :public, :no_permission do render :text => '403 Forbidden', :status => "403 Forbidden" end
end
class TestController
rescue_exception :all, :no_permission do render :action => 'error_message' end
def sample
raise NoPermission unless can_do_something?
do_some_thing
end
end
별 차이 없나? 내 생각에는 다소 깔끔해진 것 같다.
관련 소스: http://svn.myruby.net/toy/rubyonrails/plugin/rescue_exception/lib/rescue_exception.rb
Verification에서 예외 발생
ActionController::Verification은 예외 처리를 하기에 가장 좋은 위치이다. verify 메서드를 활용하면 파라메터가 부족하다든가, POST만 허용한다든가, Ajax 호출만 허용한다든가 하는 액션의 선조건(pre conditions)을 정해줄 수 있다. 그런데, 이런 조건을 만족하지 않을 때 취할 수 있는 행동이 좀 제한적이다. 위에서 말한 대표적인 에러처리 방법 2가지가 전부이다.
이를 확장해, verify에서 예외를 발생시킬 수 있다면(raise), 위에서 만든 rescue_exception과 찰떡 궁합일 것 같다.
- class AttachmentsController < ApplicationController
verify :params => [:user, :page, :Filedata], :method => :post, :only => [:create, :upload],
:raise => WrongParameter
end
그런데 구현체가 별로 좋지 않다. 몽키패칭이 되어버렸다.
관련 소스: http://svn.myruby.net/toy/rubyonrails/plugin/rescue_exception/lib/verify_and_throw.rb
소스 코드
http://svn.myruby.net/toy/rubyonrails/plugin/rescue_exception
별거 아니지만 플러그인으로 분리해보았다.
어제, 블로그를 읽다 보니, 이런 생각을 하는 사람이 나뿐이 아니었다. 비슷한 내용을 구현한 사람도 이미 있었다. 돌고~ 돌고~~.




December 27th, 2007 at 09:28 AM 이것도 기시감이+_+v