如何在回调中正确抛出异常

Q.Promise: How to throw exception in callback correctly?

本文关键字:抛出异常 回调      更新时间:2023-09-26

我这里的简单代码http://jsfiddle.net/xh6960fo/

function test () {
    var res = Q.defer();
    res.resolve('Hello');
    return res.promise;
};
test()
.then(
    function(message) {
        console.log(message);
        throw new Error('Exception!');
    },
    function (err) {
        console.log('no');
        console.error(err);
    })
.fin(function () {
    console.log('fin');
});

我需要在'then'回调中引发异常。

但是在控制台上我只看到

你好

我的异常没有升高。如何正确抛出异常?

then的异常处理程序只捕获自己的成功处理程序之前发生的错误,不包括。

...
.then(function() {
    throw new Error('error'):
})
.then(null, function(err) {
    console.log(err);
})
.fin(...)