Ruby Language Exceptions Adding information to (custom) exceptions

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Example

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


Got any Ruby Language Question?