Rails 7.1 Now Allows ErrorReporter To Handle Several Error Classes

Recently Rails introduced a new way of handling errors which removes the need of using begin..end and makes handling of multiple errors much more easier to read and write.

Read more about ErrorReporting API from here

For using error reporter we need an error subscriber.

What is a subscriber?

A Subscriber is any object with a report method defined in it. Let’s have a look -

class ErrorSubscriber
  attr_reader :error

  def initialise(error: nil)
    @error = error
  end

  def report(error, handled:, severity:, context:)
    ErrorService.report_error(error:, handled:, severity:, context:)
  end
end

Rails.error.subscribe(ErrorSubscriber.new)

The above code subscribes to our custom ErrorSubscriber class which reports errors coming from our ErrorService.

Before

Prior to the addition of error handler in Rails we used begin...end block and rescue any errors being reported which were logged in the Rails console.

  before
    set_token(10)
  rescue ArgumentError => e
    puts e.message
  end

  def set_token
    SecureRandom.base58(50)
  end

Rescue with multiple exceptions -

  EXCEPTIONS = [ArgumentError, StandarError]

  begin
    raise ArgumentError
    raise StandardError
  rescue *EXCEPTIONS => e
    puts "Error: #{e.message} occurred."
  end

After

After the change introduced in this PR, it is now possible to replace the above syntax with the handle method.

  Rails.error.handle(ArgumentError) do
    set_token(10)
  end

  def set_token
    SecureRandom.base58(50)
  end

If the block does not raise any Exception/Error then result of the block will be returned or else it returns nil.

We can override this by providing fallback which returns the fallback value if any error is raised instead of returning nil -

  3.2.2 :001 > def token
  3.2.2 :002 >   SecureRandom.base58(50)
  3.2.2 :003 > end
   => :token
  3.2.2 :004 > result = Rails.error.handle(fallback: -> { token }) do
  3.2.2 :005 >   token(10)
  3.2.2 :006 > end
   => "2n2TEr6RDjKCuoPH2xbj2Cm2AvMnEusAWw13grSAinQXnFpd5k"

Read about more options supported by ErrorHandler handle method from here

Need help on your Ruby on Rails or React project?

Join Our Newsletter