The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
What's New in Edge Rails: Better Exception Handling

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
rwdaigle

Posts: 312
Nickname: rwdaigle
Registered: Feb, 2003

Ryan is a passionate ruby developer with a strong Java background.
What's New in Edge Rails: Better Exception Handling Posted: Sep 24, 2007 8:16 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by rwdaigle.
Original Post: What's New in Edge Rails: Better Exception Handling
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by rwdaigle
Latest Posts From Ryan's Scraps

Advertisement

It’s a common pattern to redirect the user to, or render specific pages for different types of exceptions that are thrown in your application. Prior to this changeset this usually involved overloading the rescue_action_in_public method of your controllers:

1
2
3
4
5
6
7
8
9
class PostsController < ApplicationController
  def rescue_action_in_public(exception)
    case(exception)
      when ActiveRecord::RecordNotFound then render :file => '/bad_record'
      when NoMethodError then render :file => '/no_method'
      else render :file => '/error'
    end
  end
end

It’s easy to see that this can quickly grow to be an ugly mass of a case or if/else statement.

Now we’ve got a much cleaner way to map exceptions to handlers with the new rescue_from support. rescue_from maps an exception type directly to a handler method name for a very concise and direct way of dealing with exceptions:

1
2
3
4
5
6
7
8
9
10
class PostsController < ApplicationController

  # Declare exception to handler methods
  rescue_from ActiveRecord::RecordNotFound, :with => :bad_record
  rescue_from NoMethodError, :with => :show_error

  def bad_record; render :file => '/bad_record'; end
  def show_error(exception); render :text => exception.message; end

end

Note that the exception handler methods can be either no-arg methods or take the exception in question as an argument (as in show_error above).

tags: ruby, rubyonrails

Read: What's New in Edge Rails: Better Exception Handling

Topic: IE doesn't let us REST Previous Topic   Next Topic Topic: Tweets on 2007-09-21

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use