I have a complex system that utilizes async/await. My goal is to handle various types of errors from an async function within a single try/catch block. This function is called from another async function.
Unfortunately, I've been unable to successfully handle exceptions in the parent async function. When attempting to do so as shown below, I only receive a warning about an unhandled promise rejection and the catch block in the parent function never captures the error. I've even tried throwing an error without success.
const die = (message) => new Promise((resolve, reject) => reject(message));
const survive = () => new Promise((resolve, reject) => resolve(true));
const childAsync = async () => {
await survive();
try {
await die('farewell');
} catch (error) {
return Promise.reject(error);
}
try {
await die('enjoy your time');
} catch (error) {
return Promise.reject(error);
}
await survive();
};
const parentAsync = async () => {
try {
childAsync();
} catch(error) {
console.log('caught an error'); // never executed
console.log(error);
}
};
parentAsync();
I seem to be missing something crucial about async functions in order to achieve this task