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

In-depth explanation of MySQL stored procedures (in, out, inout)

1. Introduction It has been supported since versi...

Use a few interview questions to look at the JavaScript execution mechanism

Table of contents Previous words Synchronous and ...

7 native JS error types you should know

Table of contents Overview 1. RangeError 2. Refer...

Install .NET 6.0 in CentOS system using cloud server

.NET SDK Download Link https://dotnet.microsoft.c...

Analysis of the reasons why MySQL's index system uses B+ tree

Table of contents 1. What is an index? 2. Why do ...

CSS implements Google Material Design text input box style (recommended)

Hello everyone, today I want to share with you ho...

Setting up VMware vSphere in VMware Workstation (Graphic Tutorial)

VMware vSphere is the industry's leading and ...

onfocus="this.blur()" is hated by blind webmasters

When talking about the screen reading software op...

Div exceeds hidden text and hides the CSS code beyond the div part

Before hiding: After hiding: CSS: Copy code The co...

Using iframe techniques to obtain visitor QQ implementation ideas and sample code

Today at work, a friend I added temporarily asked ...

In-depth study of vue2.x--Explanation of the h function

Table of contents Solution, Summarize: vue projec...

Detailed explanation of the use of Vue3 state management

Table of contents background Provide / Inject Ext...

CentOS7 uses yum to install mysql 8.0.12

This article shares the detailed steps of install...