Warm tip: This article is reproduced from stackoverflow.com, please click
angular angular7 javascript es6-promise zonejs

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

发布于 2020-03-27 10:18:50

I have a problem in an angular 7 application. When I have a promise with a finally block, Errors are not thrown! They get swallowed without noticing, When I remove the finally-block it behaves like expected.

Here are some examples: With vanillaJS (no Angular Framework), it works like I expect it to work: As soon as you run the code, it prints my console.logs to the console and throws an "Uncaught (in promise)" error. Also see screenshot.

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');
    });

Screenshot vanillaJS enter image description here

Here we have the same code in Angular. See Stackblitz for reference: https://stackblitz.com/edit/angular-iv7cq2

When I remove the "finally", it throws the error like i expect it to do. With the "finally" it just swallows the error.

Screenshot Angular

enter image description here

Why is that? Where do I have to modify my code, so that Promises with finally-blocks also throw errors?

Questioner
Michael B
Viewed
89
timo-haas 2019-07-03 21:43

You can catch and rethrow the error after finally.

Result: Unhandled Promise rejection

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;
    });