Node.js error with context

How to add an error cause to throws in V8 9.3 and later

More context for errors

Starting with version 9.3 of the V8 Javascript engine, developers will have the option to add a new type of information when throwing a default error. Instead of providing a single argument, you’ll be able to add a kind of error-type, also called error cause, so that a handler for catching such errors can better determine from where the error originated.

To be more precise, the Error-constructor accepts a second optional parameter, which is an object of options, where the property “cause” can be used.

Let’s take a look at an example.

/**
 * A simple demonstration how
 * the syntax will benefit from
 * the error-cause option in
 * new Errors.
 * 
 * Note that the example is greatly
 * simplified to focus on the 
 * relevant changes.
 */
async function processImage(props) {
  try {
    await minifyImage(props);
  } catch (err) {
    throw new Error('image-minification', { cause: err });
  }
  try {
    await uploadImage(props);
  } catch (err) {
    throw new Error('image-upload', { cause: err });
  }
  try {
    await cleanUpCache(props);
    await notifyUser(props);
  } catch (err) {
    throw new Error('post-processing', { cause: err });
  }
}

//
// ... later in our code ...
//

async function selectAndUploadImage(props){
  try {
    await processImage(props);
  } catch (err) {
    console.error(err.cause);
    
    switch(err) {
      case 'image-minification':
        // handle the minification error,
        // which is available by accessing
        // 'err.cause'.
        break;
      case 'image-upload':
        // ...
        break;
      case 'post-processing':
        // ...
        break;
    }
  }
}

Advantage of error causes

The clear benefit of using error causes is on the one that you don’t have to define a custom Error-class to handle similar cases in your code. On the other hand, having a standard mechanism for error causes will also nicely work with debugging tools.

Available with V8 version 9.3 and later

As of writing, this change isn’t available for public usage yet, as the current latest Node.js version 16.4.2 uses the latest stable version of V8, which is 9.1. When Node.js will start using version 9.3, I’ll update this article accordingly.

Suggestions

Related

Addendum

Languages