Home > Blockchain >  Is it a good practice to always have a catch block for the await statement?
Is it a good practice to always have a catch block for the await statement?

Time:07-11

For example I have an async function:

prepAttrsRef.current.addEventListener('documentstatechanged', async (evt: CustomEvent<FlowDocumentState>) => {
if (evt.detail.draftState === 'unpublished-changes') {
  dispatch(updateIsFlowpublished(false));
  await publishPrepFlow();
}
if (evt.detail.draftState === 'all-changes-published') {
     await cleanSteps[0].selectAsync();
  }
}
await getAndDispatchPrepColumns();
});

Should I always enclose the await lines with try/catch or at least a catch to handle the potential case that the promise could be rejected? (Although I don't know if the promise will be reject or not, since I am calling the API created by others)

CodePudding user response:

It is always a good practice to handle exceptions at the point of origin to avoid hours of debugging to find out why the code is breaking. Now, having said that I believe you need to decide at what level you need to handle exceptions.

In production, you have no idea what input/parameters you might get if those are exposed to the end-user. There might be a case where the input is some value that can't be handled by the underlying API which will cause your service to fail.

enter image description here

For example,

If you wrap the entire block of code i.e. two await statements in a try-catch block, you won't know which await failed unless you have custom exceptions raised by the awaited function.

CodePudding user response:

for clean code, yes, you should do that, your function supposed to do one thing and if it fails you should let it bark(where the problem), that will help you in debugging.

if you have many try/catch in the same block, your function does many things, and that's not good practice.

this is a good example

try{
await publishPrepFlow();
}catch(error){

// throw it to handle it on a different level
throw Error('unable to publishPrepflow')

// no any action | write on log file at least ...
console.log('unable to publishPrepflow')
}

to handle all uncaught Exception & Rejected Promises

process
  .on('unhandledRejection', (reason, p) => {
    console.error(reason, 'Unhandled Rejection at Promise', p);
  })
  .on('uncaughtException', err => {
    console.error(err, 'Uncaught Exception thrown '  err.message);
  });

  • Related