2009-09-22 40 views
19

trong đoạn mã sauLàm thế nào để hiển thị loại lỗi trong ruby?

begin 
raise StandardError, 'message' 
#some code that raises a lot of exception 
rescue StandardError 
#handle error 
rescue OtherError 
#handle error 
rescue YetAnotherError 
#handle error 
end 

Tôi muốn in một cảnh báo loại và sứ điệp của các lỗi mà không cần thêm tuyên bố in cho mỗi khoản giải cứu, như

begin 
raise StandardError, 'message' 
#some code that raises a lot of exception 
rescue StandardError 
#handle error 
rescue OtherError 
#handle error 
rescue YetAnotherError 
#handle error 
??? 
print "An error of type #{???} happened, message is #{???}" 
end 

Trả lời

44
begin 
    raise ArgumentError, "I'm a description" 
rescue Exception => ex 
    puts "An error of type #{ex.class} happened, message is #{ex.message}" 
end 

Bản in: Đã xảy ra lỗi loại ArgumentError, thông báo là tôi mô tả

+3

Và sau đó nếu bạn vẫn cần xử lý cụ thể cho các loại lỗi khác nhau, bạn có thể thực hiện rằng với một trường hợp .. khi nào. – cpm

+3

Xem nó, không bắt ngoại lệ trừ khi bạn hoàn toàn nhận thức được ý nghĩa của nó. Sử dụng rescue => ex thay vì (Convention over configuration) Là một cacher mặc định. –

Các vấn đề liên quan