【问题标题】:Checkit with bookshelf, how to catch error and stop DB execution?Checkit with bookshelf,如何捕捉错误并停止数据库执行?
【发布时间】:2015-01-02 03:41:09
【问题描述】:

我正在尝试将 checkit 与书架一起使用,在添加 checkit 规则后,故意违反它们,我的 promise#catch 块似乎没有正确捕获错误。 (我也可能完全误解了 catch 的用法)

var validationRules = new Checkit({
    email: 'required',
    password: 'required'
});

var User = bookshelf.Model.extend({
    tableName: 'users',

    initialize: function() {
        this.on('saving', this.validateSave);
    },
    validateSave: function() {
        validationRules.run(this.attributes);
    }
});

User.forge({}).save().then(function(validated) {
    console.log('this shouldnt trigger');
}).catch(function(err) { // this doesnt seem to be working the way I expect
    console.log(e.message);
});

当我创建空的用户对象时,我得到了以下未处理的错误堆栈跟踪,并且还看到正在构建一个数据库查询(这可能是书架项目的一个单独问题,当您连接到“保存”时会发生什么'事件)

Possibly unhandled Checkit Errors - email: The email is required; password: The password is     required
    at checkit/checkit.js:105:23
    at tryCatch1 (bluebird/js/main/util.js:45:21)
    at Promise._callHandler (bluebird/js/main/promise.js:597:13)
    at Promise._settlePromiseFromHandler (bluebird/js/main/promise.js:607:18)
    at Promise._settlePromiseAt (checkit/node_modules/bluebird/js/main/promise.js:769:18)
    at Promise._settlePromises (checkit/node_modules/bluebird/js/main/promise.js:884:14)
    at Async._drainQueue (checkit/node_modules/bluebird/js/main/async.js:98:12)
    at Async._drainQueues (checkit/node_modules/bluebird/js/main/async.js:103:10)
    at Async.drainQueues (checkit/node_modules/bluebird/js/main/async.js:37:14)
    at process._tickCallback (node.js:415:13)
{ __cid: '__cid1',
  method: 'insert',
  options: undefined,
  bindings: [],
  sql: 'insert into `users` () values ()' }
ER_NO_DEFAULT_FOR_FIELD: Field 'email' doesn't have a default value

我对此有 2 个问题:

  1. 由于我在 knex 配置中打开了 debug: true,因此堆栈跟踪和 ER_NO_DEFAULT_FOR_FIELD 之间的块似乎是准备好的 SQL 语句。既然我引入了 Checkit 来捕获模型级别的验证错误,为什么 SQL 仍在执行?
  2. 我是否以正确的方式使用#catch 块?如果是这样,为什么我仍然会收到未处理的错误堆栈跟踪。 (看起来#catch 函数产生的e.message 实际上来自 MySQL 而不是 Checkit)如果不是,那么在这里更优雅地处理错误的正确方法是什么?

到目前为止,我的主要信息来源是 bookshelf.js 文档 (http://bookshelfjs.org/) 和 Checkit repo (https://github.com/tgriesser/checkit)

【问题讨论】:

    标签: error-handling promise model-validation bookshelf.js


    【解决方案1】:

    Checkit 返回 Promise,Promise 使用 return values 相互配合,所以如果在 checkit.run 之后没有 return,您就不会让 bookshelf 知道验证何时完成。

    Bluebird(基本承诺)让您知道您可能会遇到您不知道的拒绝。为了更正您需要更改的代码:

    validationRules.run(this.attributes);

    收件人:

    <b>return</b> validationRules.run(this.attributes);

    在您的 validateSave 函数中,这样 promise 可以链接。

    【讨论】:

    • 谢谢!做到了,不敢相信我之前没有看到。
    • @bahrieinn 我在 Bluebird 有 raised an issue,我们将讨论在这种情况下有更好的错误 - 调试这些东西应该更简单:)
    猜你喜欢
    • 1970-01-01
    • 2019-12-13
    • 2020-12-10
    • 2018-03-18
    • 1970-01-01
    • 2010-12-06
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多