Ruby Language Exceptions Adding information to (custom) exceptions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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?