Kế thừa từ StandardError (hoặc subclass của nó) — không phải từ Exception gốc.
ruby
# Pattern chuẩn: tạo base error cho library, sau đó specialise
module PaymentGateway
class Error < StandardError; end
class ConnectionError < Error; end
class InsufficientFundsError < Error
def initialize(amount, balance)
super("Need #{amount} but only have #{balance}")
@amount = amount
@balance = balance
end
attr_reader :amount, :balance
end
end
# Caller có thể rescue broad hoặc narrow:
rescue PaymentGateway::Error => e # bắt mọi lỗi payment
rescue PaymentGateway::InsufficientFundsError => e # chỉ bắt thiếu tiềnBest practice:
- Tên kết thúc bằng Error.
- Kế thừa StandardError, không phải Exception.
- Tạo 1 base error class cho mỗi library/module.
- Thêm context data qua attr_reader để caller biết chi tiết.