Adding information to custom exceptions

suggest change

It may be helpful to include additional information with an exception, e.g. for logging purposes or to allow conditional handling when the exception is caught:

class CustomError < StandardError
  attr_reader :safe_to_retry

  def initialize(safe_to_retry = false, message = 'Something went wrong')
    @safe_to_retry = safe_to_retry
    super(message)
  end
end

Raising the exception:

raise CustomError.new(true)

Catching the exception and accessing the additional information provided:

begin
  # do stuff
rescue CustomError => e
  retry if e.safe_to_retry
end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Exceptions:
*Adding information to custom exceptions

Table Of Contents