0

I read somewhere that it should be possible to catch an error that was thrown in the promise using Promise.catch, but I'm not quite getting it to work..

Here is a minimal working(or not) example I'm having issues with. I've tried to catch the error using try-catch and using Promise.catch, but neither of them seem to work. Am I missing something here?

{
function throwingFunction() {
    return new Promise(() => {
        setTimeout(() => {
            throw new Error();
        }, 1000);
    })
}
(async() => {
    try {
        await throwingFunction().catch(error => console.log("then-catch"));
    } catch(error) {
        console.log("try-catch");
    }
})()

}

The problem I am trying to solve is the following: I'm writing some tests for an application. The application throws some errors that I can then use as feedback when testing the ui.

Gamer2015
  • 195
  • 6
  • Why do you use `async` with `return new Promise()`. It makes no sense – bill.gates May 16 '22 at 22:07
  • You need to return a Promise. The callee would use async and awaits, not the promise itself. Also you'd want to reject the error for the callee to catch it – kanuos May 16 '22 at 22:08
  • @Ifaruki thank you, you're obviously right, I updated the question, the same issue still prevails though – Gamer2015 May 16 '22 at 22:10
  • @kanuos I think I do return a Promise here, what exactly do you mean? Do I really have to reject an error though? What if it happens in some code I am not allowed to modify? Even if they would reject on error, do I need to write `.catch(error => reject(error))` all the time? – Gamer2015 May 16 '22 at 22:12
  • The error was *not* thrown within the promise. It was thrown within a `setTimeout` callback. – Bergi May 16 '22 at 22:37

0 Answers0