Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

เชี่ยวชาญ Custom Exceptions ใน Ruby: คู่มือขั้นตอนละเอียด

สร้าง custom exceptions ใน Ruby ง่ายมาก แค่ทำตามขั้นตอน:

1. สร้าง Class ใหม่

Exceptions เป็น classes เหมือนทุกอย่างใน Ruby! สร้าง exception ใหม่ แค่สร้าง class inherit จาก StandardError หรือ children ของมัน

class MyError < StandardError end raise MyError 

Convention: custom exceptions ชื่อ class ลงท้าย "Error" ดีที่สุดใส่ใน module เช่น ActiveRecord::RecordNotFound และ Net::HTTP::ConnectionError

2. เพิ่ม Message

ทุก ruby exception object มี message attribute ข้อความยาวที่พิมพ์ข้างๆ exception name

เชี่ยวชาญ Custom Exceptions ใน Ruby: คู่มือขั้นตอนละเอียด ตัวอย่าง exception's message attribute

ระบุ message ตอน raise exception ได้:

raise MyError, "My message" 

เพิ่ม default message ให้ custom error class โดยเพิ่ม constructor เอง:

class MyError < StandardError def initialize(msg="My default message") super end end 

3. เพิ่ม Custom Data Attributes ให้ Exception

เพิ่ม custom data ให้ exception เหมือน class อื่นๆ เพิ่ม attribute reader และ 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 

แค่นี้! สร้าง custom error/exception ใน Ruby ไมยาก มีอย่างหนึ่งตระหนัก: เรา inherit จาก StandardError เสมอ ใน examples นั่น intentional แม้มี Exception class ใน Ruby อย่า inherit จาก Exception โดยตรง เพราะมันทำลาย expected behavior ของ rescue อ่านเพิ่มในบทความความต่าง Exception vs StandardError