节点和sequelize – > .catch(…)不能按预期方式工作
这里有一个非常简单的例子。 在这种情况下,“标记”是模型上的只读属性,当您尝试写入时会引发错误。 这只是为了强制一个错误来显示.catch(…)如何不被调用。 下面是非常简单的示例代码(名称,说明,运行时间都是variables设置为静态值之前,我们得到这个代码):
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请求只是在那里旋转,控制台输出很清楚地显示exception只是冒泡而不被捕获。
我在Sequelize调用中错过了.catch(…)
谢谢。
以下是来自exception堆栈输出的相关信息。 文本“这是一个只读属性”是当您尝试写入该属性时生成和抛出的错误消息。
Unhandled rejection Error: This is a read-only property
问题是.catch
只捕获承诺parsing处理程序中抛出的问题(即在您的示例中传递给.then
的函数)。
看看这些评论,看起来这条抛出错误的行是:
models.TANServer.create({ name : name, description : description, defaultUpTime : defaultUpTime, token : "apple" })
如果是这样,则不会返回任何承诺,因此.catch
和.catch
expression式永远不会运行,并且不会返回任何响应。
解决的办法是改变.create
所以它返回一个失败的承诺(使用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 });