I currently have a server and API set up using Node & Express. My project has expanded further than I initially thought, so structure is becoming more and more important - as is error handling.
To avoid clutter, I've minimized the code that's within my routing functions. The issue I have is that I'm not sure how I should be handling errors that bubble up within the different methods and external API calls that I need to make to achieve the desired functionality in my routing function. I want to structure my project in a way that my routing functions contain minimal code, and my server/API does not crash AND discontinues executing all methods when an error is found anywhere.
Instead, I'd like my server to send a response to the client that has the error message found at any step, and give the corresponding status, as well as exit any functions that were called within it.
I.e: Example given below:
I've seen posts recommending adding try/catch
blocks after the await
calls, to create a pattern like: try { await taskA();} catch { ... }
, but I'm not sure how to get the bubbling up of errors that I'd like to eventually send to my routing function so it can give the proper response to the client.
// routes.js
router.get('/',function(req,res,next)){
util.topLevel()
.then((response)=> {
if(response.good) res.status(200).send(...);
else res.status(500).send(error_msg);
})
.catch((err)=> {
console.log('unexpected error...');
res.end();
}
// util.js
// topLevel is the function we call from our routing method
async function topLevel(){
await taskA();
await taskB();
}
// taskA & B retrieve data needed to return back to topLevel to complete
// request, and will be making calls to other functions
async function taskA(){
await leafTaskA();
await leafTaskB();
}
async function taskB(){
await leafTaskC();
await leafTaskD();
}
// Where each leafTask may/may not make a 3rd party API request, but no calls
// to external functions. They end up getting the raw values
async function leafTasks A-D(){ logic };
Aucun commentaire:
Enregistrer un commentaire