Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 979
Michael B Avatar asked Oct 20 '25 14:10

Michael B


1 Answers

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;
    });
like image 69
timo-haas Avatar answered Oct 22 '25 04:10

timo-haas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!