2016-05-16 71 views
2

我是nodejs的新手,试图编写第一个较大的项目。不幸的是,当我在Q fullfilment句柄中犯了一个错误时,我无法与nodejs退出并没有错误。nodejs + Q承诺:在履行处理中没有引用异常

实施例:

var Q = require('q'); 
    function test1() { 
     var deferred = Q.defer(); 
     deferred.resolve(); 
     return(deferred.promise); 
} 

console.log("Start"); 
test1() 
.then (function(ret) { 
    imnotexisting; //this should be shown as Reference Exception 
    console.log("OK"); 
}, function(err) { 
    console.log("FAIL"); 
}); 
console.log("Stop"); 

'

的输出将是:

Start 
Stop 

与由于 “imnotexisting” 部分没有语法/参考或者任何其他错误。 除了fullfilment句柄外,同样的错误会抛出erorr,因为它应该如此。

我在Ubuntu上使用nodejs 4.4.4。

+0

同样适用于nodejs 6.1.0 –

+0

任何帮助或评论?这个问题使得我所有的拼写错误都变得至关重要 - 因为我的项目现在非常复杂 - 有许多异步路径和长循环 - 应用程序内部的一些执行路径失败,没有错误信息。跟踪他们需要年龄... –

回答

0

OK,我发现这一点:

One sometimes-unintuive aspect of promises is that if you throw an exception in the fulfillment handler, it will not be caught by the error handler. 
(...) 
To see why this is, consider the parallel between promises and try/catch. We are try-ing to execute foo(): the error handler represents a catch for foo(), while the fulfillment handler represents code that happens after the try/catch block. That code then needs its own try/catch block. 

我们需要添加.fail部分如下:

var Q = require('q'); 
    function test1() { 
     var deferred = Q.defer(); 
     deferred.resolve(); 
     return(deferred.promise); 
} 

console.log("Start"); 
test1() 
.then (function(ret) { 
    imnotexisting; 
    console.log("OK"); 
}, function(err) { 
    console.log("FAIL"); 
}) 
.fail (function(err) { 
    console.log("Error: "+err); 
}); 
console.log("Stop"); 

,其结果是: 开始 停止 错误:的ReferenceError: imnotexisting未定义