Exception handling is where a codebase either tells you clearly what went wrong or hides it. A good style guide section on exceptions is short and opinionated. Here is a set of rules that keeps errors honest.
Rescue specific classes
A bare rescue catches StandardError and everything under it, including typos that raise NoMethodError. Name the errors you actually expect.
# Avoid
begin
response = client.fetch(order_id)
rescue
nil
end
# Prefer
begin
response = client.fetch(order_id)
rescue Timeout::Error, Errno::ECONNREFUSED => e
logger.warn("Order lookup failed: #{e.message}")
nil
end
Never rescue Exception. It includes signals and SystemExit, so it can stop a process from shutting down cleanly.
Define your own error hierarchy
Give a library or service one base error, then subclass it. Callers can rescue the whole family or a single case.
module Billing
class Error < StandardError; end
class CardDeclined < Error; end
class InvalidAmount < Error; end
end
raise Billing::InvalidAmount, "Amount must be positive" if amount <= 0
Do not use exceptions for flow control
If a condition is normal, such as a record not being found by a search form, return a value or use a method like find_by that returns nil. Exceptions are for situations the current method cannot handle.
Use method level rescue
Inside a method you can drop the begin keyword, which keeps the happy path flat.
def load_config(path)
YAML.safe_load(File.read(path))
rescue Errno::ENOENT
{}
end
ensure and retry
- Use
ensurefor cleanup that must happen, such as closing a file or releasing a lock. Do notreturnfrom anensureblock, because it silently discards any exception in flight. - When you use
retry, always cap the number of attempts, otherwise a persistent failure becomes an infinite loop.
attempts = 0
begin
attempts += 1
api.publish(event)
rescue Net::ReadTimeout
retry if attempts < 3
raise
end
Keep the original error
When you wrap a low level error in your own, Ruby records the original as cause automatically if you raise inside the rescue block. Keep it that way, and avoid swallowing errors without at least logging them.