首页 > 解决方案 > 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 关键字,但从未遇到过这种情况。

我正在运行的内容:

为什么即使我救援它也会引发错误,如何防止引发错误?

标签: rubymongodberror-handlingmongoid

解决方案


我不确定为什么即使你救了它也会升起,但我会回答“如何防止它”部分。

在你的mongoid.yml,你需要设置

raise_not_found_error: false

有关示例,请参阅Mongoid 文档中的此部分。


推荐阅读