Error Reporting in Rails Applications
This guide introduces ways to manage errors in a Rails application.
After reading this guide, you will know:
- How to use Rails' error reporter to capture and report errors.
- How to create custom subscribers for your error-reporting service.
1. Error Reporting
The Railserrorreporterprovides a standard way to collect errors that occur in your application andreport them to your preferred service or location (e.g. you could report theerrors to a monitoring service such asSentry).
It aims to replace boilerplate error-handling code like this:
begindo_somethingrescueSomethingIsBroken=>errorMyErrorReportingService.notify(error)endwith a consistent interface:
Rails.error.handle(SomethingIsBroken)dodo_somethingendRails wraps all executions (such as HTTPrequests,jobs, andrails runner invocations) in the error reporter,so any unhandled errors raised in your app will automatically be reported toyour error-reporting service via their subscribers.
For HTTP requests, errors present inActionDispatch::ExceptionWrapper.rescue_responsesare not reported as they do not result in server errors (500) and generally aren't bugs that need to be addressed.
This means that third-party error-reporting libraries no longer need to insert aRack middleware or do any monkey-patching to captureunhandled errors. Libraries that useActiveSupport can also usethis to non-intrusively report warnings that would previously have been lost inlogs.
Using the Rails error reporter is optional, as other means of capturingerrors still work.
1.1. Subscribing to the Reporter
To use the error reporter with an external service, you need asubscriber. Asubscriber can be any Ruby object with areport method. When an error occursin your application or is manually reported, the Rails error reporter will callthis method with the error object and some options.
Some error-reporting libraries, such as Sentry'sand Honeybadger's,automatically register a subscriber for you.
You may also create a custom subscriber. For example:
# config/initializers/error_subscriber.rbclassErrorSubscriberdefreport(error,handled:,severity:,context:,source:nil)MyErrorReportingService.report_error(error,context:context,handled:handled,level:severity)endendAfter defining the subscriber class, you can register it by calling theRails.error.subscribemethod:
Rails.error.subscribe(ErrorSubscriber.new)You can register as many subscribers as you wish. Rails will call them in theorder in which they were registered.
It is also possible to unregister a subscriber by callingRails.error.unsubscribe.This may be useful if you'd like to replace or remove a subscriber added by oneof your dependencies. Bothsubscribe andunsubscribe can take either asubscriber or a class as follows:
subscriber=ErrorSubscriber.newRails.error.unsubscribe(subscriber)# orRails.error.unsubscribe(ErrorSubscriber)The Rails error reporter will always call registered subscribers,regardless of your environment. However, many error-reporting services onlyreport errors in production by default. You should configure and test your setupacross environments as needed.
1.2. Using the Error Reporter
Rails error reporter has four methods that allow you to report methods indifferent ways:
Rails.error.handleRails.error.recordRails.error.reportRails.error.unexpected
1.2.1. Reporting and Swallowing Errors
TheRails.error.handlemethod will report any error raised within the block. It will thenswallowthe error, and the rest of your code outside the block will continue as normal.
result=Rails.error.handledo1+"1"# raises TypeErrorendresult# => nil1+1# This will be executedIf no error is raised in the block,Rails.error.handle will return the resultof the block, otherwise it will returnnil. You can override this by providingafallback:
user=Rails.error.handle(fallback:->{User.anonymous})doUser.find(params[:id])end1.2.2. Reporting and Re-raising Errors
TheRails.error.recordmethod will report errors to all registered subscribers and thenre-raisethe error, meaning that the rest of your code won't execute.
Rails.error.recorddo1+"1"# raises TypeErrorend1+1# This won't be executedIf no error is raised in the block,Rails.error.record will return the resultof the block.
1.2.3. Manually Reporting Errors
You can also manually report errors by callingRails.error.report:
begin# coderescueStandardError=>eRails.error.report(e)endAny options you pass will be passed on to the error subscribers.
1.2.4. Reporting Unexpected Errors
You can report any unexpected error by callingRails.error.unexpected.
When called in production, this method will return nil after the error isreported and the execution of your code will continue.
When called in development or test, the error will be wrapped in a new error class (toensure it's not being rescued higher in the stack) and surfaced to the developerfor debugging.
For example:
defeditifpublished?Rails.error.unexpected("[BUG] Attempting to edit a published article, that shouldn't be possible")falseend# ...endThis method is intended to gracefully handle any errors that may occur inproduction, but that aren't anticipated to be the result of typical use.
1.3. Error-reporting Options
The reporting APIs#handle,#record, and#report support the followingoptions, which are then passed along to all registered subscribers:
handled: aBooleanto indicate if the error was handled. This is set totrueby default.#recordsets this tofalse.severity: aSymboldescribing the severity of the error. Expected valuesare::error,:warning, and:info.#handlesets this to:warning,while#recordsets it to:error.context: aHashto provide more context about the error, like request oruser detailssource: aStringabout 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", forinstance. Your subscriber can use the source to ignore errors you aren'tinterested in.
Rails.error.handle(context:{user_id:user.id},severity: :info)do# ...end1.4. Setting Context Globally
In addition to setting context through thecontext option, you can useRails.error.set_context.For example:
Rails.error.set_context(section:"checkout",user_id:@user.id)Any context set this way will be merged with thecontext option
Rails.error.set_context(a:1)Rails.error.handle(context:{b:2}){raise}# The reported context will be: {:a=>1, :b=>2}Rails.error.handle(context:{b:3}){raise}# The reported context will be: {:a=>1, :b=>3}1.5. Filtering by Error Classes
WithRails.error.handle andRails.error.record, you can also choose to onlyreport errors of certain classes. For example:
Rails.error.handle(IOError)do1+"1"# raises TypeErrorend1+1# TypeErrors are not IOErrors, so this will *not* be executedHere, theTypeError will not be captured by the Rails error reporter. Onlyinstances ofIOError and its descendants will be reported. Any other errorswill be raised as normal.
1.6. Disabling Notifications
You can prevent a subscriber from being notified of errors for the duration of ablock by callingRails.error.disable.Similarly tosubscribe andunsubscribe, you can pass in either thesubscriber itself, or its class.
Rails.error.disable(ErrorSubscriber)do1+"1"# TypeError will not be reported via the ErrorSubscriberendThis can also be helpful for third-party error reporting services who maywant to manage error handling a different way, or higher in the stack.
2. Error-reporting Libraries
Error-reporting libraries can register their subscribers in aRailtie:
moduleMySdkclassRailtie<::Rails::Railtieinitializer"my_sdk.error_subscribe"doRails.error.subscribe(MyErrorSubscriber.new)endendendIf you register an error subscriber, but still have other error mechanismslike a Rack middleware, you may end up with errors reported multiple times. Youshould either remove your other mechanisms or adjust your report functionalityso it skips reporting an error it has seen before.