在哪里拯救网络连接错误:在模型中还是在控制器中?
我有一个模型,需要先访问外部网站,然后才能创建模型实例。什么被认为是错误恢复的最佳实践?请注意,由于我尚未创建模型,因此我在模型中使用了类方法。
挽救模型(而不是控制器)中的错误感觉是正确的,但是将错误传达给控制器的最佳方法是什么?以下代码的问题是模型返回 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) 并将其返回到控制器代码。这会让我将错误分配给模型实例[对吗?],但我不确定这是公共 API 的一部分。如果可以,您会如何编写它?)
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.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
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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一定要在控制器中拯救它。管制员是交通警察,负责将交通引导到适当的地方。与外部服务器的连接以及故障时的相应错误处理是流量处理的一部分 - 因此是 100% 控制器职责。
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.