When things go wrong
raise throws an exception, rescue catches it, ensure runs always (cleanup!). Good programs define their own error family – then callers can catch “all timelog errors” without swallowing unrelated ones:
module Timelog
class Error < StandardError; end
class ParseError < Error; end
class OverlapError < Error; end
end
begin
raise Timelog::ParseError, "line 7 is not a time entry"
rescue Timelog::Error => e
"caught: #{e.class}: #{e.message}"
endException or return value? Rule of thumb: nil for “can happen normally” (a line doesn't match the pattern), exception for “something is fundamentally wrong here” (an entry ends before it starts). Always inherit from StandardError, never from Exception directly – or you'll catch Ctrl-C too. And put the family into your module (Timelog::ParseError) so it never clashes with anyone else's.
For transient errors (networks!) there's retry: it jumps back to the start of the begin block:
class TimelogError < StandardError; end
attempts = 0
flaky_service = lambda do
attempts += 1
raise TimelogError, "network error" if attempts < 3
"data received (attempt #{attempts})"
end
begin
flaky_service.call
rescue TimelogError
retry if attempts < 5
endReal retry code waits longer between attempts (backoff) – there is no sleep in the browser:
rescue TimelogError
wait = 2 ** attempt # 1s, 2s, 4s, 8s ...
sleep(wait)
retry if attempt < 5sync_with_retry(service, max:): it calls service.call. If the service raises a TimelogError, it tries up to max times in total – after that the error propagates (simply don't retry anymore). On success it returns the result.class TimelogError < StandardError; end
# def sync_with_retry(service, max:)
# attempts = 0
# begin
# ...
# rescue TimelogError
# ...
# end
# end