我有一个模型需要在创建模型实例之前访问外部网站。错误恢复的最佳实践是什么?请注意,由于我还没有创建模型,所以我在模型中使用了一个类方法。
挽救模型(而不是控制器)中的错误感觉是对的,但是将错误传达给控制器的最佳方式是什么?以下代码的问题是模型返回 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 的一部分。这会起作用吗,如果是,你会怎么写?)