ruby - Mongoid::Errors::DocumentNotFound is raised even after rescuing

标签 ruby mongodb error-handling mongoid

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

我正在运行:
  • Ruby 2.5
  • Rails 5.2
  • Mongoid 7.0.1

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

    最佳答案

    我不知道为什么即使在营救它时也将其抬起,但是我将回答“如何预防”部分。

    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/

    相关文章:

    angularjs - ngCordova错误不断发生

    listview - 在App中显示ListView时出现Flutter错误

    error-handling - std::error::FromError 惯用用法

    ruby - 在不同的进程中生成命令提示符并在 Windows 上发送/接收命令

    mongodb - 使用 Testcontainers + Quarkus + MongoDB 进行集成测试

    Ruby popen3 和 ANSI 颜色

    mysql - Slamdata:如何根据日期查找累计和

    php - 是否有用于 codeigniter 的 mongodb 支持的用户身份验证库?

    mysql - 编写一个 Rails 事件记录查询来通过与两个表关联来获取所有项目?

    ruby-on-rails - 使用 Paypal Express 的 Paypal 定期付款