Rescue from dispatching 4

Posted by pratik
on Sunday, July 20

This question gets asked quite a few times, if there’s an easy way to handle exceptions raised while dispatching a request (routing exceptions, invalid method etc.) gracefully and show a customized error page. After this commit, there is.

rescue_from to the rescue

Now you can handle those exceptions inside your application.rb like :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ApplicationController < ActionController::Base
  rescue_from ActionController::RoutingError, :with => :route_not_found
  rescue_from ActionController::MethodNotAllowed, :with => :invalid_method
  
  private
  
  def route_not_found
    render :text => 'What the fuck are you looking for ?', :status => :not_found
  end
  
  def invalid_method
    message = "Now, did your mom tell you to #{request.request_method.to_s.upcase} that ?"
    render :text => message, :status => :method_not_allowed
  end
end

Just make sure you don’t raise another exception from your rescue_from action!

Comments

Leave a response

  1. leethalJuly 20, 2008 @ 03:12 PM

    Hey, nice! Especially the :status => :not_found, I thought you had to do :status => 404

  2. Fredrik WJuly 20, 2008 @ 03:47 PM

    Sweet, I waited for this post since you said you’d blog in #rubyonrails.

    Sweet stuff, can’t wait for the next release! :)

  3. Anil WadghuleJuly 21, 2008 @ 07:43 PM

    Sweet!

  4. hiphapisJuly 24, 2008 @ 02:46 AM

    puck!! :)

Comment