在 Angular 中,带有 finally()-Block 的 Promise 没有正确拒绝

In Angular a Promise with a finally()-Block does not reject properly

我在 angular 7 应用程序中遇到问题。 当我用 finally 块 承诺 时,不会抛出错误!它们在没有注意到的情况下被吞下,当我删除 finally-block 时,它的行为与预期的一样

这里有一些例子: 使用 vanillaJS(无 Angular 框架),它的工作方式与我期望的一样: 一旦你 运行 代码,它就会将我的 console.logs 打印到控制台并抛出 "Uncaught (in promise)" 错误。另请参阅屏幕截图。

Promise.resolve()
    .then(() => {
        console.log('then');
        return Promise.reject('This is an error. Please show up in the console, thank you.');
    })
    .finally(() => {
        console.log('finally');
    });

屏幕截图 vanillaJS

此处我们在 Angular 中有相同的代码。请参阅 Stackblitz 以供参考: https://stackblitz.com/edit/angular-iv7cq2

当我删除 "finally" 时,它会像我预期的那样抛出错误。使用 "finally" 它只是吞下了错误。

截图Angular

这是为什么?我必须在哪里修改我的代码,以便带有 finally 块的 Promises 也会抛出错误?

this_link 你可以得到一个最终吞下错误的想法:因为

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is discarded:

我主要在 python 上工作,以上内容取自 this python 文档,因为它在所有语言中都是一样的: 但是如果你想引发和处理错误,那么你可以使用这个语法:

return Promise.resolve()
    .then(() => {
        console.log('then');
        return Promise.reject('This is an error. Please show up in the console, thank you.');
    }).catch ((error) =>{
        console.log('error');

    }).finally(() => {
        console.log('finally');
    });

您最终可以在 之后捕获并重新抛出错误。

结果:未处理的承诺拒绝

Promise.resolve()
    .then(() => {
        console.log('then');
        return Promise.reject('This is an error. Please show up in the console, thank you.');
    })
    .finally(() => {
        console.log('finally');
    }).catch(err => {
        throw err;
    });