向(自定義)例外新增資訊
包含具有異常的附加資訊可能會有所幫助,例如用於記錄目的或在捕獲異常時允許條件處理:
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
提出例外:
raise CustomError.new(true)
捕獲異常並訪問提供的其他資訊:
begin
# do stuff
rescue CustomError => e
retry if e.safe_to_retry
end