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.
Inherit from StandardError (or a subclass) — not from Exception directly.
ruby
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 can rescue broadly or narrowly:
rescue PaymentGateway::Error => e
rescue PaymentGateway::InsufficientFundsError => eBest practices:
- Name exceptions ending in Error.
- Inherit from StandardError, not Exception.
- Create one base error class per library/module.
- Attach context data via attr_reader so callers have detail.