我这里有一个非常简单的例子。在这种情况下,'token' 是模型上的只读属性,当您尝试编写它时会引发错误。这只是为了强制错误显示 .catch(...) 是如何不被调用的。非常简单的示例代码如下(名称、描述、正常运行时间都是在我们获得此代码之前设置为静态值的变量):

models.TANServer.create({
    name : name,
    description : description,
    defaultUpTime : defaultUpTime,
    token : "apple"
})
.then( function( server ){

    if( !server ){
        res.statusCode = 400;
        res.end( "unknown error creating new server entry" );
        return;
    }

    res.statusCode = 200;
    res.end( JSON.stringify( server ) );
    return;

}).catch( function( reason ){
    res.statusCode = 500;
    res.end( "This should print out " + reason + " but is never called as the error stack goes to console, and nothing ever is caught." );
    return;
});

catch 永远不会被调用,http 请求只是在那里旋转,控制台输出非常清楚地显示异常只是冒泡而没有被捕获。

我在 Sequelize 调用中缺少 .catch(...) 什么?

谢谢。

异常堆栈输出的相关信息如下。文本“这是只读属性”是我在尝试写入该属性时生成并抛出的错误消息。
Unhandled rejection Error: This is a read-only property

最佳答案

问题是 .catch 只捕获在 promise 解析处理程序中抛出的问题(即,在您的示例中传递给 .then 的函数)。

查看评论,似乎抛出错误的行是:

models.TANServer.create({
  name : name,
  description : description,
  defaultUpTime : defaultUpTime,
  token : "apple"
})

如果是这种情况,则不会返回 promise ,因此永远不会运行 .then.catch 表达式,并且不会返回任何响应。

解决方法是更改​​ .create 使其返回失败的 promise (使用 Promise.reject )而不是抛出错误

如果我无法修复 .create 怎么办?

如果 .create 是第三方代码,或者如果您大部分时间都需要同步错误,但这种情况很痛苦,您可以将调用包装在 try / catch 语句或 Promise.resolve 块中:
try {
  models.TANServer.create(...).then(...).catch(...);
catch (e) {
  // A synchronous exception happened here
}

// Alternatively (and much better IMO):
Promise.resolve().then(() => {
  // Any synchronous errors here will fail the promise chain
  // triggering the .catch
  return models.TANServer.create(...);
}).then(server => {
  // Use server here
}).catch(reason => {
  // All errors show up here
});

关于node.js - Node 和 Sequelize -> .catch(...) 没有按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43729063/

10-12 01:14
查看更多