Skip to content

Commit 5a720a6

Browse files
committed
Add Order Matters For Rescue From Blocks as a rails til
1 parent 481784d commit 5a720a6

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99

1010
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1111

12-
_904 TILs and counting..._
12+
_905 TILs and counting..._
1313

1414
---
1515

@@ -560,6 +560,7 @@ _904 TILs and counting..._
560560
- [Mark For Destruction](rails/mark-for-destruction.md)
561561
- [Merge A Scope Into An ActiveRecord Query](rails/merge-a-scope-into-an-activerecord-query.md)
562562
- [Migrating Up Down Up](rails/migrating-up-down-up.md)
563+
- [Order Matters For `rescue_from` Blocks](rails/order-matters-for-rescue-from-blocks.md)
563564
- [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md)
564565
- [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md)
565566
- [Polymorphic Path Helpers](rails/polymorphic-path-helpers.md)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Order Matters For `rescue_from` Blocks
2+
3+
In a Rails controller, you can declare any number of [`rescue_from`
4+
blocks](https://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html)
5+
for capturing and responding to execeptions that are raised by your
6+
application.
7+
8+
```ruby
9+
class BooksController < BaseController
10+
11+
rescue_from ForbiddenAction do |e|
12+
render json: { error: e.message }.to_json, status: 403
13+
end
14+
15+
rescue_from StandardError do |e|
16+
render json: { error: e.message }.to_json, status: 500
17+
end
18+
19+
def index
20+
# ...
21+
22+
raise ForbiddenAction, "Which rescue_from is this going to hit?"
23+
end
24+
end
25+
```
26+
27+
The potential problem with above is the ordering of the two `rescue_from`
28+
blocks. Assume that `ForbiddenAction` is a subclass of the `StandardError`
29+
class -- this is likely the case for exceptions you declare in your app. The
30+
top `rescue_from` will never get hit because everything that subclasses
31+
`StandardError` will be trapped by the bottom `rescue_from`.
32+
33+
These `rescue_from` blocks are applied bottom-up. That means you have to
34+
consider the class hierarchy when structuring your code. In the above code
35+
example, if we flip the two of them around, we will then get what we are
36+
expecting.

0 commit comments

Comments
 (0)