我有一个Rails Controller ,此方法作为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中一直使用救援关键字,但从未遇到过。
我正在运行:
为什么即使我营救它也会引发错误,又如何防止引发错误呢?
最佳答案
我不知道为什么即使在营救它时也将其抬起,但是我将回答“如何预防”部分。
在mongoid.yml
中,您需要设置
raise_not_found_error: false
有关示例,请参见Mongoid文档中的this section。
关于ruby - Mongoid::Errors::DocumentNotFound is raised even after rescuing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50458970/