Tạo custom exception trong Ruby rất dễ. Chỉ cần làm theo các bước:
1. Tạo Class mới
Exception là class, như mọi thứ trong Ruby! Tạo loại exception mới, chỉ cần tạo class kế thừa từ `StandardError`, hoặc con cháu của nó.
class MyError < StandardError; end
raise MyError
Theo quy ước, custom exception tên class kết thúc bằng "Error". Cũng nên đặt custom exception trong module. Tức class error cuối cùng trông như: `ActiveRecord::RecordNotFound` và `Net::HTTP::ConnectionError`.
2. Thêm message
Mọi ruby exception object có attribute `message`. Là đoạn text dài in ra bên cạnh tên exception.
Ví dụ attribute message của exception.
Chỉ định message khi raise exception:
raise MyError, "My message"
Thêm default message cho custom error class bằng constructor riêng:
class MyError < StandardError
def initialize(msg="My default message")
super
end
end
3. Thêm custom data attributes cho exception
Thêm custom data vào exception như bất kỳ class nào. Thêm attribute reader và update constructor.
class MyError < StandardError
attr_reader :thing
def initialize(msg="My default message", thing="apple")
@thing = thing
super(msg)
end
end
begin
raise MyError.new("my message", "my thing")
rescue => e
puts e.thing # "my thing"
end
Xong! Tạo custom error/exception trong Ruby không khó. Một điều lưu ý: ví dụ luôn kế thừa từ `StandardError`. Đó là cố ý. Ruby có class `Exception`, nhưng bạn KHÔNG BAO GIỜ nên kế thừa trực tiếp từ nó. Xem bài về khác biệt giữa Exception và StandardError để hiểu thêm.