mirror of
https://github.com/jbranchaud/til
synced 2026-01-04 23:58:01 +00:00
Add Rescue From With A Separate Method as a Rails til
This commit is contained in:
@@ -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)
|
||||
|
||||
33
rails/rescue-from-with-a-separate-method.md
Normal file
33
rails/rescue-from-with-a-separate-method.md
Normal file
@@ -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.
|
||||
Reference in New Issue
Block a user