2017-06-21 60 views
2

一個同事最近告訴我,這是一個反模式(recordActiveRecord):這是一個錯誤處理反模式?

begin 
    record.save! 
    do_something_else 
    rescue => e 
    puts "Unable to save" 
    end 

...我應該做這個:

if record.save 
    do_something_else 
    else 
    puts "Unable to save" 
    end 

他的理由是我m使用流量控制的異常(我同意這很糟糕),但我相信這是一種典型的錯誤處理模式。

想法?

+0

不要對控制流使用異常。提出異常要比檢查更爲昂貴。 – Makoto

+0

相關/ dupe:https://softwareengineering.stackexchange.com/q/189222/54997 – Makoto

回答

4

這是一個反模式,因爲有更好的方法來檢查記錄的有效性,而不是運行save!(如果它無效,會產生錯誤)。

這可能是你的同事在越來越:

if record.save 
    do_something_else 
    else 
    puts record.errors.full_messages 
    end 

你看,這裏存在,因爲有較少的迂迴的方式來做到這一點使用誤差控制流的只是沒有好處。

您也可以獨立於保存嘗試運行驗證。當調用record.valid?時,將填充(字符串)errors.full_messages數組。 record.save內部調用record.valid?

if record.valid? 
    record.save # or save!; by this point you can assume the record is valid 
else 
    puts record.errors.full_messages 
end 
+2

在你的第二種情況'save(false)'或現在'save(validate:false)'會更好,因爲'valid?'有已經驗證了該記錄,「保存」將再次不必要地進行。 – engineersmnky