0
我有一個模型需要訪問外部網站才能創建模型的實例。什麼被視爲錯誤恢復的最佳實踐?請注意,由於我沒有創建模型,因此我在模型中使用了類方法。哪裏可以解救網絡連接錯誤:在模型或控制器中?
救救模型中的錯誤(而不是控制器)感覺不錯,但是傳達錯誤到控制器的最好方法是什麼?用下面的代碼的問題是,該模型返回nil,所以控制器無法提供任何提示用戶哪些失敗:
class MyModel < ActiveRecord::Base
def self.lookup(address)
begin
return web_lookup(address)
rescue SocketError
return nil
end
end
end
class MyModelsController < ApplicationController
def create
info = MyModel.lookup(params[:address])
if info
MyModel.create(:info => info)
else
flash_message('cannot lookup info') # I'd like to tell the user what failed here
end
end
end
你會如何處理這個? (PS:我可以在我的模型代碼中調用MyModel.new(:info => info)並將其返回給控制器代碼。這會讓我爲模型實例指定一個錯誤[right?],但是,我不確定這是公共API的一部分,是否會起作用,如果是這樣,你會如何編寫它?)
我意識到網絡訪問應該在延遲工作或同等處理下處理,以便從根本上改變事物的結構。儘管如此,你的回答很有道理。 –