where to rescue network connection error: in model or controller?
I have a model that requires accessing an external web site before an instance of the model can be created. What is considered best practices for error recovery? Note that since I haven't created the model, I use a class method in the model.
Rescuing the error in the model (rather than the controller) feels right, but then what's the best way to convey the error to the controller? The problem with the following code is that the model returns nil, so the controller can't offer any hint to the user what failed:
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.开发者_StackOverflowlookup(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
How would you approach this?
(P.S.: I could possibly call MyModel.new(:info => info) in my model code and return that to the controller code. This would let me assign an error to the model instance [right?], but I'm not sure that's part of the public API. Would that work, and if so, how would you write it?)
Definitely rescue this in the controller. The controller is the traffic-cop, responsible for directing traffic to the appropriate place. The connection to an external server, and corresponding error handling on failure is part of that traffic handling - therefore 100% controller duties.
精彩评论