我这里有一个非常简单的例子。在这种情况下,'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
block :
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 and sequelize -> .catch(...) 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729063/