-1
\$\begingroup\$

Im new to javascript programming and i am required to make a web app. Node.js will be used as the js runtime environment. In order to minimize the amount of time needed for debugging as the app develops I would like to implement a robust error handling scheme. However, due to my limited background I am not sure if what I am implementing is best practise or if it is even adequate. So any feedback will be accepted.

The function is asynchronous and will use catch to detect if any errors occurred while operating. A try-catch statement will be used to catch any errors. This was done in order to allow for individual error identification from the functions. My aim is to propagate the errors up to the calling function that will handle it in the highest level catch statement (in my case where it is logged *this will change eventually). Any feedback?

create: async function(req, res) {
  let data = JSON.parse(req.body.data);
  let result;
  let request_body;
  let sub_networks_lora;
  try {
    request_body = sub_network_api_request_data(data, 1);
    result = await lora_app_server.create_applications(request_body)
      .catch(err => {
        //Error updating application on lora app server
        throw err;
      });
    await db_sub_networks.create_sub_network(result.data.id, data.sub_network_name, data.network_id)
      .catch(err => {
        throw err;
        //Error creating sub network in database 
      });
    sub_networks_lora = await get_sub_networks()
      .catch(err => {
        throw err;
        //Error getting networks from lora app server
      })
    sub_networks_lora = JSON.stringify(sub_networks_lora);
    res.status(200).send({
      sub_networks_lora
    });
  } catch (err) {
    console.log(err)
  } finally {}
}

\$\endgroup\$
  • 3
    \$\begingroup\$ Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see How to get the best value out of Code Review: Asking Questions for guidance on writing good question titles. \$\endgroup\$ – Toby Speight Nov 2 '18 at 15:53
  • \$\begingroup\$ What is the expected result if more than one Promise object within try is rejected? \$\endgroup\$ – guest271314 Nov 2 '18 at 22:53
  • \$\begingroup\$ @guest271314 the throw will prevent any of the other async functions from running. Hence only one of the functions can throw an error. \$\endgroup\$ – nicholas mitchell Nov 3 '18 at 5:43
  • \$\begingroup\$ The code at the question returns expected result? \$\endgroup\$ – guest271314 Nov 3 '18 at 5:49
  • \$\begingroup\$ @guest271314 from the errors I throwed it did. I just wanted some suggestions to make it 'better' or more standard \$\endgroup\$ – nicholas mitchell Nov 3 '18 at 15:27
1
\$\begingroup\$

try...catch will only handle one error, the remainder, if any, will be uncaught errors.

One approach would be to use Promise.all() and Array.prototype.map() within the async function, throw errors from within .then() chained to create() to .catch() if necessary.

async function create() {
  let results = {resolved:[],rejected:[]};
  let a = new Promise(resolve=>setTimeout(resolve,2000,1));
  let b = Promise.reject(2);
  let c = Promise.reject(3);
  await Promise.all(
    Object.entries({a,b,c})
   .map(([k,p])=>
    // `resolve` or `reject` an object having key
    // set to variable declaration; e.g., `a`, `b`, `c`
    // so we know which `Promise` is resolved or rejected
    p.then(d=>results.resolved.push({[k]:d}))
    .catch(e=>results.rejected.push({[k]:e}))
   )
  );
  return results;
}

create()
.then(({resolved,rejected})=>{
  console.log({resolved}); 
  // `throw` errors to `.catch()` if necessary, here
  if (rejected.length) {
    throw new Error(
    JSON.stringify(rejected))
  }
})
.catch(e=>console.error({caught:e}));

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.