Adding information to custom exceptions
suggest changeIt 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents