Active Support Error Reporter¶↑
ActiveSupport::ErrorReporter is a common interface for error reporting services.
To rescue and report any unhandled error, you can use thehandle method:
Rails.error.handledodo_something!end
If an error is raised, it will be reported and swallowed.
Alternatively, if you want to report the error but not swallow it, you can userecord:
Rails.error.recorddodo_something!end
Both methods can be restricted to handle only a specific error class:
maybe_tags =Rails.error.handle(Redis::BaseError) {redis.get("tags") }
Constants
| DEFAULT_RESCUE | = | [StandardError].freeze |
| DEFAULT_SOURCE | = | "application" |
| SEVERITIES | = | %i(error warning info) |
| UnexpectedError | = | Class.new(Exception) |
Attributes
| [RW] | debug_mode | |
| [RW] | logger |
Class Public methods
new(*subscribers, logger: nil)Link
Instance Public methods
add_middleware(middleware)Link
Add a middleware to modify the error context before it is sent to subscribers.
Middleware is added to a stack of callables run on an error’s execution context before passing to subscribers. Allows creation of entries in error context that are shared by all subscribers.
A context middleware receives the same parameters asreport. It must return a hash - the middleware stack returns the hash after it has run through all middlewares. A middleware can mutate or replace the hash.
Rails.error.add_middleware(-> (error,context) {context.merge({foo::bar }) })
disable(subscriber)Link
Prevent a subscriber from being notified of errors for the duration of the block. You may pass in the subscriber itself, or its class.
This can be helpful for error reporting service integrations, when they wish to handle any errors higher in the stack.
handle(*error_classes, severity: :warning, context: {}, fallback: nil, source: DEFAULT_SOURCE)Link
Evaluates the given block, reporting and swallowing any unhandled error. If no error is raised, returns the return value of the block. Otherwise, returns the result offallback.call, ornil iffallback is not specified.
# Will report a TypeError to all subscribers and return nil.Rails.error.handledo1+'1'end
Can be restricted to handle only specific error classes:
maybe_tags =Rails.error.handle(Redis::BaseError) {redis.get("tags") }
Options¶↑
:severity- This value is passed along to subscribers to indicate how important the error report is. Can be:error,:warning, or:info. Defaults to:warning.:context- Extra information that is passed along to subscribers. For example:Rails.error.handle(context: {section:"admin" })do# ...end
:fallback- A callable that provideshandle‘s return value when an unhandled error is raised. For example:user =Rails.error.handle(fallback:-> {User.anonymous })doUser.find_by(params)end
:source- This value is passed along to subscribers to indicate the source of the error. Subscribers can use this value to ignore certain errors. Defaults to"application".
# File activesupport/lib/active_support/error_reporter.rb, line 79defhandle(*error_classes,severity::warning,context: {},fallback:nil,source:DEFAULT_SOURCE)error_classes =DEFAULT_RESCUEiferror_classes.empty?yieldrescue*error_classes=>errorreport(error,handled:true,severity:severity,context:context,source:source)fallback.calliffallbackend
record(*error_classes, severity: :error, context: {}, source: DEFAULT_SOURCE)Link
Evaluates the given block, reporting and re-raising any unhandled error. If no error is raised, returns the return value of the block.
# Will report a TypeError to all subscribers and re-raise it.Rails.error.recorddo1+'1'end
Can be restricted to handle only specific error classes:
tags =Rails.error.record(Redis::BaseError) {redis.get("tags") }
Options¶↑
:severity- This value is passed along to subscribers to indicate how important the error report is. Can be:error,:warning, or:info. Defaults to:error.:context- Extra information that is passed along to subscribers. For example:Rails.error.record(context: {section:"admin" })do# ...end
:source- This value is passed along to subscribers to indicate the source of the error. Subscribers can use this value to ignore certain errors. Defaults to"application".
# File activesupport/lib/active_support/error_reporter.rb, line 115defrecord(*error_classes,severity::error,context: {},source:DEFAULT_SOURCE)error_classes =DEFAULT_RESCUEiferror_classes.empty?yieldrescue*error_classes=>errorreport(error,handled:false,severity:severity,context:context,source:source)raiseend
report(error, handled: true, severity: handled ? :warning : :error, context: {}, source: DEFAULT_SOURCE)Link
Report an error directly to subscribers. You can use this method when the block-basedhandle andrecord methods are not suitable.
Rails.error.report(error)
Theerror argument must be an instance ofException.
Rails.error.report(Exception.new("Something went wrong"))
Otherwise you can useunexpected to report an error which does accept a string argument.
# File activesupport/lib/active_support/error_reporter.rb, line 233defreport(error,handled:true,severity:handled?:warning::error,context: {},source:DEFAULT_SOURCE)returniferror.instance_variable_defined?(:@__rails_error_reported)raiseArgumentError,"Reported error must be an Exception, got: #{error.inspect}"unlesserror.is_a?(Exception)ensure_backtrace(error)unlessSEVERITIES.include?(severity)raiseArgumentError,"severity must be one of #{SEVERITIES.map(&:inspect).join(", ")}, got: #{severity.inspect}"endfull_context =@context_middlewares.execute(error,context:ActiveSupport::ExecutionContext.to_h.merge(context|| {}),handled:,severity:,source: )disabled_subscribers =ActiveSupport::IsolatedExecutionState[self]@subscribers.eachdo|subscriber|unlessdisabled_subscribers&.any? {|s|s===subscriber }subscriber.report(error,handled:handled,severity:severity,context:full_context,source:source)endrescue=>subscriber_errorifloggerlogger.fatal("Error subscriber raised an error: #{subscriber_error.message} (#{subscriber_error.class})\n"+subscriber_error.backtrace.join("\n") )elseraiseendendwhileerrorunlesserror.frozen?error.instance_variable_set(:@__rails_error_reported,true)enderror =error.causeendnilend
set_context(...)Link
subscribe(subscriber)Link
Register a new error subscriber. The subscriber must respond to
report(Exception, handled: Boolean, severity: (:error OR :warning OR :info), context: Hash, source: String)
Thereport methodshould never raise an error.
unexpected(error, severity: :warning, context: {}, source: DEFAULT_SOURCE)Link
Either report the given error when in production, or raise it when in development or test.
When called in production, after the error is reported, this method will return nil and execution will continue.
When called in development, the original error is wrapped in a different error class to ensure it’s not being rescued higher in the stack and will be surfaced to the developer.
This method is intended for reporting violated assertions about preconditions, or similar cases that can and should be gracefully handled in production, but that aren’t supposed to happen.
The error can be either an exception instance or aString.
example: def edit if published? Rails.error.unexpected("[BUG] Attempting to edit a published article, that shouldn't be possible") return false end # ... end# File activesupport/lib/active_support/error_reporter.rb, line 146defunexpected(error,severity::warning,context: {},source:DEFAULT_SOURCE)error =RuntimeError.new(error)iferror.is_a?(String)if@debug_modeensure_backtrace(error)raiseUnexpectedError,"#{error.class.name}: #{error.message}",error.backtrace,cause:errorelsereport(error,handled:true,severity:severity,context:context,source:source)endend
unsubscribe(subscriber)Link
Unregister an error subscriber. Accepts either a subscriber or a class.
subscriber =MyErrorSubscriber.newRails.error.subscribe(subscriber)Rails.error.unsubscribe(subscriber)# orRails.error.unsubscribe(MyErrorSubscriber)