我有一个Rails控制器,这个方法被触发为before_action:
def authenticate_user
Knock::AuthToken.new(token: token).entity_for(User)
rescue Mongoid::Errors::DocumentNotFound
render nothing: true, status: 401
end
即使我可以验证它是否正在挽救错误(在救援声明下触发了一个byebug断点),它仍然可以在以下情况下立即被提升:
Mongoid::Errors::DocumentNotFound (
message:
Document(s) not found for class User with id(s) 1.
summary:
When calling User.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): 1 ... (1 total) and the following ids were not found: 1.
resolution:
Search for an id that is in the database or set the Mongoid.raise_not_found_error configuration option to false, which will cause a nil to be returned instead of raising this error when searching for a single id, or only the matched documents when searching for multiples.):
app/controllers/api/base_controller.rb:12:in `authenticate_user'
我多年来一直在Ruby中使用rescue关键字并且从未遇到过这种情况。
我在跑什么:
为什么即使我拯救它也会引发错误,如何防止错误被引发?
答案 0 :(得分:0)
我不确定为什么即使你拯救它也会被提升,但我会回答"如何预防它"一部分。
在mongoid.yml
中,您需要设置
raise_not_found_error: false
有关示例,请参阅Mongoid文档中的this section。