{ Greg Molnar } | Rails' rescue_from

Ask questions Research chat →

https://greg.molnar.io/blog/rails-rescue_from/ · scraped

rails ruby

Attachments

Scraped Content

— 235 words · 2026-02-14 17:42:08 UTC ·

Excerpt

rescue_from is a very useful method in Rails. It lets us to catch exceptions and pass them to a callback or a block. A typical usecase is to handle ActiveRecord::RecordNotFound errors like in this example: ```plain text FooController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, with: not_found private def notfound message = "Foo with ID #{params[:id]} not found." logger.error message redirect_to not_found_url, info: message end end ``` In the example above whenever an ActiveRecord::RecordNotFound raised in the scope of the FooController it will be caught and the notfound method will log the event than redirect to the notfound page with a message to display in the browser. Since rescue_from works with a block too we can refactor the above as follows: ```plain text FooController < ActionController::Base rescue_from ActiveRecord::RecordNotFound do |exception| message = "Foo with ID #{params[:id]} not found." logger.error message
rescue_from is a very useful method in Rails. It lets us to catch exceptions and pass them to a callback or a block. A typical usecase is to handle ActiveRecord::RecordNotFound errors like in this example: ```plain text FooController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, with: not_found private def notfound message = "Foo with ID #{params[:id]} not found." logger.error message redirect_to not_found_url, info: message end end ``` In the example above whenever an ActiveRecord::RecordNotFound raised in the scope of the FooController it will be caught and the notfound method will log the event than redirect to the notfound page with a message to display in the browser. Since rescue_from works with a block too we can refactor the above as follows: ```plain text FooController < ActionController::Base rescue_from ActiveRecord::RecordNotFound do |exception| message = "Foo with ID #{params[:id]} not found." logger.error message redirect_to not_found_url, info: message end end ``` Another case when rescue_from comes handy is when we use cancan for authorization and we want to handle the authorization errors. We can do so by add the following to the application controller: ```plain text rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, :alert => exception.message end ``` As you see in this case we display the exception message set by cancan. If you want to use rescue_from from in a class which does not inherit from ActionController::Base you just need to mixin the ActiveSupport::Rescuable: ```plain text class Foo include ActiveSupport::Rescuable end ```

Visibility

Visible to everyone

Reading Status

Related Bookmarks

My Note


Saved!

Annotations

Export as Markdown
+ Annotate selection

Add Annotation