Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion guides/source/documents.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@
-
name: Error Reporting in Rails Applications
url: error_reporting.html
description: This guide introduces ways to manage exceptions that occur in Ruby on Rails applications.
description: This guide introduces ways to manage errors that occur in Ruby on Rails applications.
-
name: Debugging Rails Applications
url: debugging_rails_applications.html
Expand Down
192 changes: 155 additions & 37 deletions guides/source/error_reporting.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Error Reporting in Rails Applications
========================

This guide introduces ways to manage exceptions that occur in Ruby on Rails applications.
This guide introduces ways to manage errors in a Rails application.

After reading this guide, you will know:

Expand All @@ -13,11 +13,16 @@ After reading this guide, you will know:
--------------------------------------------------------------------------------

Error Reporting
------------------------
---------------

The Rails [error reporter](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html) provides a standard way to collect exceptions that occur in your application and report them to your preferred service or location.
The Rails [error
reporter](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html)
provides a standard way to collect errors that occur in your application and
report them to your preferred service or location (e.g. you could report the
errors to a monitoring service such as
Sentry).

The error reporter aims to replace boilerplate error-handling code like this:
It aims to replace boilerplate error-handling code like this:

```ruby
begin
Expand All @@ -35,17 +40,32 @@ Rails.error.handle(SomethingIsBroken) do
end
```

Rails wraps all executions (such as HTTP requests, jobs, and `rails runner` invocations) in the error reporter, so any unhandled errors raised in your app will automatically be reported to your error-reporting service via their subscribers.
Rails wraps all executions (such as HTTP
requests,
[jobs](active_job_basics.html), and [rails runner](command_line.html#bin-rails-runner) invocations) in the error reporter,
so any unhandled errors raised in your app will automatically be reported to
your error-reporting service via their subscribers.

This means that third-party error-reporting libraries no longer need to insert a Rack middleware or do any monkey-patching to capture unhandled exceptions. Libraries that use ActiveSupport can also use this to non-intrusively report warnings that would previously have been lost in logs.
This means that third-party error-reporting libraries no longer need to insert a
[Rack](rails_on_rack.html) middleware or do any monkey-patching to capture
unhandled errors. Libraries that use [Active
Support](https://api.rubyonrails.org/classes/ActiveSupport.html) can also use
this to non-intrusively report warnings that would previously have been lost in
logs.

Using the Rails' error reporter is not required. All other means of capturing errors still work.
NOTE: Using the Rails error reporter is optional, as other means of capturing
errors still work.

### Subscribing to the Reporter

To use the error reporter, you need a _subscriber_. A subscriber is any object with a `report` method. When an error occurs in your application or is manually reported, the Rails error reporter will call this method with the error object and some options.
To use the error reporter with an external service, you need a _subscriber_. A
subscriber can be any Ruby object with a `report` method. When an error occurs
in your application or is manually reported, the Rails error reporter will call
this method with the error object and some options.

Some error-reporting libraries, such as [Sentry's](https://github.com/getsentry/sentry-ruby/blob/e18ce4b6dcce2ebd37778c1e96164684a1e9ebfc/sentry-rails/lib/sentry/rails/error_subscriber.rb) and [Honeybadger's](https://docs.honeybadger.io/lib/ruby/integration-guides/rails-exception-tracking/), automatically register a subscriber for you. Consult your provider's documentation for more details.
NOTE: Some error-reporting libraries, such as Sentry's
and Honeybadger's,
automatically register a subscriber for you.

You may also create a custom subscriber. For example:

Expand All @@ -58,23 +78,51 @@ class ErrorSubscriber
end
```

After defining the subscriber class, register it by calling [`Rails.error.subscribe`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-subscribe) method:
After defining the subscriber class, you can register it by calling the
[`Rails.error.subscribe`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-subscribe)
method:

```ruby
Rails.error.subscribe(ErrorSubscriber.new)
```

You can register as many subscribers as you wish. Rails will call them in turn, in the order in which they were registered.
You can register as many subscribers as you wish. Rails will call them in the
order in which they were registered.

It is also possible to unregister a subscriber by calling
[`Rails.error.unsubscribe`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-unsubscribe).
This may be useful if you'd like to replace or remove a subscriber added by one
of your dependencies. Both `subscribe` and `unsubscribe` can take either a
subscriber or a class as follows:

```ruby
subscriber = ErrorSubscriber.new
Rails.error.unsubscribe(subscriber)
# or
Rails.error.unsubscribe(ErrorSubscriber)
```

NOTE: The Rails error-reporter will always call registered subscribers, regardless of your environment. However, many error-reporting services only report errors in production by default. You should configure and test your setup across environments as needed.
NOTE: The Rails error reporter will always call registered subscribers,
regardless of your environment. However, many error-reporting services only
report errors in production by default. You should configure and test your setup
across environments as needed.

### Using the Error Reporter

There are three ways you can use the error reporter:
Rails error reporter has four methods that allow you to report methods in
different ways:

* `Rails.error.handle`
* `Rails.error.record`
* `Rails.error.report`
* `Rails.error.unexpected`

#### Reporting and Swallowing Errors

[`Rails.error.handle`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-handle) will report any error raised within the block. It will then **swallow** the error, and the rest of your code outside the block will continue as normal.
The
[`Rails.error.handle`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-handle)
method will report any error raised within the block. It will then **swallow**
the error, and the rest of your code outside the block will continue as normal.

```ruby
result = Rails.error.handle do
Expand All @@ -84,7 +132,9 @@ result # => nil
1 + 1 # This will be executed
```

If no error is raised in the block, `Rails.error.handle` will return the result of the block, otherwise it will return `nil`. You can override this by providing a `fallback`:
If no error is raised in the block, `Rails.error.handle` will return the result
of the block, otherwise it will return `nil`. You can override this by providing
a `fallback`:

```ruby
user = Rails.error.handle(fallback: -> { User.anonymous }) do
Expand All @@ -94,7 +144,10 @@ end

#### Reporting and Re-raising Errors

[`Rails.error.record`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-record) will report errors to all registered subscribers and then re-raise the error, meaning that the rest of your code won't execute.
The
[`Rails.error.record`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-record)
method will report errors to all registered subscribers and then **re-raise**
the error, meaning that the rest of your code won't execute.

```ruby
Rails.error.record do
Expand All @@ -103,11 +156,13 @@ end
1 + 1 # This won't be executed
```

If no error is raised in the block, `Rails.error.record` will return the result of the block.
If no error is raised in the block, `Rails.error.record` will return the result
of the block.

#### Manually Reporting Errors

You can also manually report errors by calling [`Rails.error.report`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-report):
You can also manually report errors by calling
[`Rails.error.report`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-report):

```ruby
begin
Expand All @@ -117,39 +172,64 @@ rescue StandardError => e
end
```

Any options you pass will be passed on the error subscribers.
Any options you pass will be passed on to the error subscribers.

### Error-reporting Options
#### Reporting Unexpected Errors

You can report any unexpected error by calling
[`Rails.error.unexpected`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-unexpected").

All 3 reporting APIs (`#handle`, `#record`, and `#report`) support the following options, which are then passed along to all registered subscribers:
When called in production, this method will return nil after the error is
reported and the execution of your code will continue.

- `handled`: a `Boolean` to indicate if the error was handled. This is set to `true` by default. `#record` sets this to `false`.
- `severity`: a `Symbol` describing the severity of the error. Expected values are: `:error`, `:warning`, and `:info`. `#handle` sets this to `:warning`, while `#record` sets it to `:error`.
- `context`: a `Hash` to provide more context about the error, like request or user details
- `source`: a `String` about the source of the error. The default source is `"application"`. Errors reported by internal libraries may set other sources; the Redis cache library may use `"redis_cache_store.active_support"`, for instance. Your subscriber can use the source to ignore errors you aren't interested in.
When called in development, the error will be wrapped in a new error class (to
ensure it's not being rescued higher in the stack) and surfaced to the developer
for debugging.

For example:

```ruby
Rails.error.handle(context: { user_id: user.id }, severity: :info) do
def edit
if published?
Rails.error.unexpected("[BUG] Attempting to edit a published article, that shouldn't be possible")
false
end
# ...
end
```

### Filtering by Error Classes
NOTE: This method is intended to gracefully handle any errors that may occur in
production, but that aren't anticipated to be the result of typical use.

With `Rails.error.handle` and `Rails.error.record`, you can also choose to only report errors of certain classes. For example:
### Error-reporting Options

The reporting APIs `#handle`, `#record`, and `#report` support the following
options, which are then passed along to all registered subscribers:

- `handled`: a `Boolean` to indicate if the error was handled. This is set to
`true` by default. `#record` sets this to `false`.
- `severity`: a `Symbol` describing the severity of the error. Expected values
are: `:error`, `:warning`, and `:info`. `#handle` sets this to `:warning`,
while `#record` sets it to `:error`.
- `context`: a `Hash` to provide more context about the error, like request or
user details
- `source`: a `String` about the source of the error. The default source is
`"application"`. Errors reported by internal libraries may set other sources;
the Redis cache library may use `"redis_cache_store.active_support"`, for
instance. Your subscriber can use the source to ignore errors you aren't
interested in.

```ruby
Rails.error.handle(IOError) do
1 + '1' # raises TypeError
Rails.error.handle(context: { user_id: user.id }, severity: :info) do
# ...
end
1 + 1 # TypeErrors are not IOErrors, so this will *not* be executed
```

Here, the `TypeError` will not be captured by the Rails error reporter. Only instances of `IOError` and its descendants will be reported. Any other errors will be raised as normal.

### Setting Context Globally

In addition to setting context through the `context` option, you can use the [`#set_context`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-set_context) API. For example:
In addition to setting context through the `context` option, you can use
[`Rails.error.set_context`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-set_context).
For example:

```ruby
Rails.error.set_context(section: "checkout", user_id: @user.id)
Expand All @@ -165,9 +245,44 @@ Rails.error.handle(context: { b: 3 }) { raise }
# The reported context will be: {:a=>1, :b=>3}
```

### For Libraries
### Filtering by Error Classes

With `Rails.error.handle` and `Rails.error.record`, you can also choose to only
report errors of certain classes. For example:

```ruby
Rails.error.handle(IOError) do
1 + '1' # raises TypeError
end
1 + 1 # TypeErrors are not IOErrors, so this will *not* be executed
```

Here, the `TypeError` will not be captured by the Rails error reporter. Only
instances of `IOError` and its descendants will be reported. Any other errors
will be raised as normal.

### Disabling Notifications

You can prevent a subscriber from being notified of errors for the duration of a
block by calling
[`Rails.error.disable`](https://api.rubyonrails.org/classes/ActiveSupport/ErrorReporter.html#method-i-disable).
Similarly to `subscribe` and `unsubscribe`, you can pass in either the
subscriber itself, or its class.

```ruby
Rails.error.disable(ErrorSubscriber) do
1 + '1' # TypeError will not be reported via the ErrorSubscriber
end
```

NOTE: This can also be helpful for third-party error reporting services who may
want to manage error handling a different way, or higher in the stack.

Error-reporting Libraries
------------------------

Error-reporting libraries can register their subscribers in a `Railtie`:
Error-reporting libraries can register their subscribers in a
[Railtie](https://api.rubyonrails.org/classes/Rails/Railtie.html):

```ruby
module MySdk
Expand All @@ -179,4 +294,7 @@ module MySdk
end
```

If you register an error subscriber, but still have other error mechanisms like a Rack middleware, you may end up with errors reported multiple times. You should either remove your other mechanisms or adjust your report functionality so it skips reporting an exception it has seen before.
NOTE: If you register an error subscriber, but still have other error mechanisms
like a Rack middleware, you may end up with errors reported multiple times. You
should either remove your other mechanisms or adjust your report functionality
so it skips reporting an error it has seen before.