ruby - Mongoid::Errors::DocumentNotFound 即使在救援之后也会引发
问题描述
我有一个 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 关键字,但从未遇到过这种情况。
我正在运行的内容:
- 红宝石 2.5
- 导轨 5.2
- Mongoid 7.0.1
为什么即使我救援它也会引发错误,如何防止引发错误?
解决方案
我不确定为什么即使你救了它也会升起,但我会回答“如何防止它”部分。
在你的mongoid.yml
,你需要设置
raise_not_found_error: false
有关示例,请参阅Mongoid 文档中的此部分。
推荐阅读
- java - 在一定延迟后需要帮助从 Web URL 下载文件
- scala - 如何将按第一个元素排序的元组列表分组到包含重叠和非重叠元组的两个列表中
- java - 为什么一定要加双引号?
- javascript - Angular 7+:如何只允许上传包含 utf-8 内容的文件?
- facebook - Facebook 图形 API 上缺少 instagram_business_account ID
- javascript - 使用 webpack 获取 svg fir 图像 src 返回 304
- java - 如何获取文件中每一行的最后一个单词并将其放入另一个文件的每一行
- java - 返回值反转的java集合
- python - 用于自定义表单数据的 Django REST 框架序列化程序
- typescript - 在我的控制器中使用模型中定义的实例方法