From c448814c16020854410675ce27efb4aa8c007839 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 27 Aug 2021 09:43:23 -0500 Subject: [PATCH] Add Rescue From With A Separate Method as a Rails til --- README.md | 3 +- rails/rescue-from-with-a-separate-method.md | 33 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 rails/rescue-from-with-a-separate-method.md diff --git a/README.md b/README.md index cc2c568..33a3a6e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1149 TILs and counting..._ +_1150 TILs and counting..._ --- @@ -731,6 +731,7 @@ _1149 TILs and counting..._ - [Render The Response Body In Controller Specs](rails/render-the-response-body-in-controller-specs.md) - [Replace An Index With A Unique Index](rails/replace-an-index-with-a-unique-index.md) - [Rescue From](rails/rescue-from.md) +- [Rescue From With A Separate Method](rails/rescue-from-with-a-separate-method.md) - [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md) - [Rollback A Specific Migration Out Of Order](rails/rollback-a-specific-migration-out-of-order.md) - [Rounding Numbers With Precision](rails/rounding-numbers-with-precision.md) diff --git a/rails/rescue-from-with-a-separate-method.md b/rails/rescue-from-with-a-separate-method.md new file mode 100644 index 0000000..ce1d872 --- /dev/null +++ b/rails/rescue-from-with-a-separate-method.md @@ -0,0 +1,33 @@ +# Rescue From With A Separate Method + +In an earlier post on [`rescue_from`](rescue_from.md), I showed how you can +write an exception handler with a block argument. + +If instead you'd prefer to implement the exception handler as a separate +method, you can do that by passing +[`rescue_from`](http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html) +a `with` keyword argument. This too will behave as a catch-all for a particular +exception raised in your controller. + +Here is what that can look like: + +```ruby +class ApplicationController < ActionController::Base + rescue_from User::NotAuthorized, with: :handle_unauthorized_user + + def index + # ... + end + + private + + def handle_unauthorized_user(exception) + # respond with some Not Authorized page + end +end +``` + +If the `User::NotAuthorized` exception bubbles up to the `rescue_from`, then it +will hand that exception off to the `handle_unauthorized_user` method. We can +include whatever logic and monitoring we want here and then render an +appropriate response.