I'm having trouble figuring out how to properly send an Express route handler response from an error generated and caught within nested try/catch blocks.
In the code below, I would like all execution of the route handler to cease if the inner Try/Catch 3 block catches an error, which will return a status 404 error. At this time, when an error is caught in Try/Catch 3, the route handler continues to execute subsequent code in Code Block A, catching and return a status 400 error in Try/Catch 1. The route hanlder then sends this 400 status response. How can I have the route handler return the Try/Catch Block 3 404 response and, therefore, never execute the code in Code Block A?
I've tried modifying return statements in various places, but can't seem to get the route handler to solely return an error caught within the inner Try/Catch 3. Can anybody see, with relative ease, where it is that I'm failing to properly return or manage the propagation of errors?
app.get("/endpoint/url", async(req, res) => {
// Try/Catch 1
try {
// Define an async function
const queryApiFunc = async() => {
// Try/Catch 3
try {
let results = await axios({
// Axios Query to API
})
if (/*condition is met*/)
throw "No results found";
}
catch (e) {
if (e === "No results found") {
res.statusMessage = e;
return res.status(404).end();;
}
}
}
// Try/Catch 2
try {
// Call the defined async function
await queryApiFunc();
} catch (e) {
return e;
}
// Code Block A
// contains another async call to API
// generates 400 status error
// Code Block A
} catch (e) {
return e;
}
}