2009-09-22 18 views
19

w poniższym kodzieJak wyświetlić typ błędu w 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 

chcę wydrukować ostrzeżenie stwierdzające rodzaj i komunikat błędu bez dodawania instrukcji print każdej z klauzul ratowniczych, jak

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 

Odpowiedz

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

Wydruki: wystąpił błąd typu ArgumentError, wiadomość jest opis Jestem

+3

A jeśli nadal potrzebujesz specjalnej obsługi dla różnych typów błędów, możesz zrobić to z przypadkiem .. kiedy. – cpm

+3

Uważaj, nie łapaj wyjątku, chyba że jesteś całkowicie świadomy tego, co to oznacza. Zamiast tego użyj rescue => ex (Konwencja przez konfigurację) Jako domyślny cacher. –

Powiązane problemy