Skip to content

Commit 2fded36

Browse files
committed
[ci skip] Add docs for error context middleware
1 parent a3b37ff commit 2fded36

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

guides/source/error_reporting.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,35 @@ Rails.error.handle(context: { b: 3 }) { raise }
248248
# The reported context will be: {:a=>1, :b=>3}
249249
```
250250

251+
### Setting Context with Error Context Middleware
252+
253+
The ErrorReporter has its own middleware stack for modifying the error context before sending to subscribers.
254+
Use this to make changes to error context that can be seen by all error subscribers, instead of replicating
255+
common functionality inside subscribers.
256+
257+
This is especially useful for gems that want to add common context to error messages without requiring modifications
258+
to error subscribers, or to add data to error context that is specific to your app. The concerns of "set error context"
259+
and "send data to error tracker" should be separated between middleware and subscribers.
260+
261+
Context middleware runs after global context set by `Rails.error.set_context` is applied to the context hash.
262+
263+
Context middleware receives the same parameters as `Rails.error.report`. The middleware stack returns the hash
264+
after running all middleware - each middleware can mutate the context hash and should return the new context hash.
265+
266+
```ruby
267+
class MyErrorContextMiddleware
268+
def call(error, context:, handled:, severity:, source:)
269+
context.merge({ foo: :bar })
270+
context
271+
end
272+
end
273+
274+
Rails.error.add_middleware(MyErrorContextMiddleware.new) # Append the middleware to the error context stack
275+
276+
Rails.error.report(error, context: {bar: :baz}) # Report an error with some context
277+
# The reported context will be { foo: :bar, bar: :baz }
278+
```
279+
251280
### Filtering by Error Classes
252281

253282
With `Rails.error.handle` and `Rails.error.record`, you can also choose to only

0 commit comments

Comments
 (0)