【问题标题】:Mongoid::Errors::DocumentNotFound is raised even after rescuingMongoid::Errors::DocumentNotFound 即使在救援之后也会引发
【发布时间】:2018-05-22 02:34:27
【问题描述】:

我有一个 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 中使用救援关键字,但从未遇到过这种情况。

我在做什么:

  • Ruby 2.5
  • Rails 5.2
  • Mongoid 7.0.1

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

【问题讨论】:

  • 你有什么问题?
  • @sawa 对不起,我认为这是含蓄的,但我会澄清一下。为什么即使我救援它似乎也会引发错误,我该如何防止引发错误?我不记得在获救时有过这样的错误“冒泡”。

标签: ruby mongodb error-handling mongoid


【解决方案1】:

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

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

raise_not_found_error: false

有关示例,请参阅 Mongoid 文档中的 this section

【讨论】:

  • 在“本节”链接上获得 404。
  • @JulienLamarche 抱歉,看起来旧链接已失效。我将其更新为较新的。
猜你喜欢
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多