A more elegant error handling method in JavaScript async await

A more elegant error handling method in JavaScript async await

background

A new colleague joined the team and found that our team code standard requires adding try...catch to async await. He felt very confused. If there were many (not concentrated), wouldn't it be necessary to add a lot of places? Isn't that inelegant?

Why error handling?

JavaScript is a single-threaded language. If try...catch is not added, an error will be reported directly and execution will not continue. Of course, it does not mean that you must wrap your code with try...catch. Using try...catch means that you know that the code at this location is likely to report an error, so you use try...catch to capture and process it, and let the program continue to execute.

I understand that when we execute async await, we usually run in an asynchronous scenario. This scenario should not block the process, so it is recommended to use try...catch.

async await more graceful error handling

But it is true as that colleague said, adding try...catch is not a very elegant behavior. So I Googled it and found How to write async await without try-catch blocks in Javascript. This article mentioned a more elegant way to handle it and encapsulated it into a library - await-to-js. This library has only one function, and we can fully apply this function to our business, as shown below:

/**
 * @param { Promise } promise
 * @param { Object= } errorExt - Additional Information you can pass to the err object
 * @return { Promise }
 */
export function to<T, U = Error> (
  promise: Promise<T>,
  errorExt?: object
): Promise<[U, undefined] | [null, T]> {
  return promise
    .then<[null, T]>((data: T) => [null, data]) // Execution is successful, the first item of the returned array is null. The second is the result.
    .catch<[U, undefined]>((err: U) => {
      if (errorExt) {
        Object.assign(err, errorExt);
      }

      return [err, undefined]; // Execution failed, the first item in the returned array is the error message, the second item is undefined
    });
}

export default to;

There is a prerequisite knowledge point here: await is waiting for the return value of a Promise.

Normally, the await command is followed by a Promise object, which returns the result. If it is not a Promise object, the corresponding value is returned directly.

So we just need to take advantage of the characteristics of Promise and return different arrays in promise.then and promise.catch respectively. When fulfilled, the first item of the returned array is null, and the second one is the result. When rejected, the first item in the returned array is the error message, and the second item is undefined. When using it, you can tell whether there is an error by judging whether the first item is empty. The specific usage is as follows:

import to from 'await-to-js';
// If you use CommonJS (ie NodeJS environment), it should be:
// const to = require('await-to-js').default;

async function asyncTaskWithCb(cb) {
     let err, user, savedTask, notification;

     [ err, user ] = await to(UserModel.findById(1));
     if(!user) return cb('No user found');

     [ err, savedTask ] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
     if(err) return cb('Error occurred while saving task');

    if(user.notificationsEnabled) {
       [ err ] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
       if(err) return cb('Error while sending notification');
    }

    if(savedTask.assignedUser.id !== user.id) {
       [ err, notification ] = await to(NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you'));
       if(err) return cb('Error while sending notification');
    }

    cb(null, savedTask);
}

summary

I personally think it is necessary to add error handling in async await, but there are more solutions than just try...catch. By leveraging the features of async await and Promise, we can handle async await errors more elegantly.

Summarize

This concludes this article about a more elegant error handling method for async await in JavaScript. For more information about elegant error handling with async await, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use async and await correctly in JS loops
  • How to use async await elegantly in JS
  • A simple and in-depth study of async and await in JavaScript
  • The use and methods of async and await in JavaScript
  • Detailed explanation of JavaScript Promise and Async/Await
  • How to use async and await in JS

<<:  Solve the problem of combining AND and OR in MySQL

>>:  Implementation of deploying war package project using Docker

Recommend

Installation tutorial of mysql 8.0.11 compressed version under win10

This article shares the installation tutorial of ...

MySQL 8.0.22 decompression version installation tutorial (for beginners only)

Table of contents 1. Resource download 2. Unzip t...

Detailed explanation of Vue's monitoring properties

Table of contents Vue monitor properties What is ...

Summary of some tips for bypassing nodejs code execution

Table of contents 1. child_process 2. Command exe...

Solution to MySQL Chinese garbled characters problem

1. The Chinese garbled characters appear in MySQL...

Sharing of web color contrast and harmony techniques

Color contrast and harmony In contrasting conditi...

Some conclusions on the design of portal website focus pictures

Focus images are a way of presenting content that ...

Practical record of Vue3 combined with TypeScript project development

Table of contents Overview 1. Compositon API 1. W...

Details of the order in which MySQL reads my.cnf

Table of contents The order in which MySQL reads ...

Vue sample code for online preview of office files

I'm working on electronic archives recently, ...

JavaScript to achieve all or reverse selection function

This article shares the specific code of JavaScri...

Vue component organization structure and component registration details

Table of contents 1. Component Organization 2. Co...