0

I am trying to catch an error that may be thrown within the catch of another promise. (sorry if that is confusing...)

async function throwingError () { throw new Error('this error needs to be caught'); // I don't know if I need to return, throw or something else. This function may or may not have an error }; async function mainFunction () { promiseFunction() .catch(error => { throwingError(); // I've tried throw throwingError() and return Promise.reject(throwingError()); }); }; mainFunction().catch(error => `caught: ${console.error}`); 

Right now, it doesn't catch the error.
From what I know, this doesn't work because the promises finish at different times, but I'm not sure.

2 Answers 2

1

Your mainFunction needs to return a Promise. What you're missing is the return statement. You also need to return throwingError() in the catch block.

Without the return statement, the value returned by your mainFunction is a Promise that always resolves to undefined

async function mainFunction () { return promiseFunction() .catch(error => { return throwingError(); }); }; 
Sign up to request clarification or add additional context in comments.

Comments

0

You need to return promise.

function throwingError () { throw new Error('this error needs to be caught'); } function mainFunction () { return new Promise((resolve, reject) => { reject(throwingError()) }) }; mainFunction().catch(error => console.log(`caught: ${error}`));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.