Your error just says 'save failed'? Keep the reason with cause

When you catch an error and throw a new one with a clearer message, pass the original in the cause option. Per MDN, the cause property holds the original reason, and it has worked across browsers since September 2021.

Published 2 min read#Web development#Developer tools

A customer writes to you, "it won't take my order", and you open the logs to find one line: "Saving the order failed." The real reason, a dropped database connection or a missing field, got lost in a catch block you wrote to make the message clearer. By the end of this article you will know how to keep the clearer message and the reason together.

What is the cause property?

The cause property is a property on any Error that holds the original reason the error happened. You set it with the cause option when you create a new Error.

The MDN page on Error.cause says its value is whatever you passed in options.cause, and that it may not be present at all. It also says it has been available across browsers since September 2021.

Why does the reason get lost?

The reason gets lost because we catch the error and throw a new one with a message we understand, and forget to put the original inside it.

The mistake is human and logical: a message like "connection reset" does not help whoever reads the logs, so we write "Saving the order failed." But the original error, with its stack, goes away at the last line of the catch, and when you hunt for the problem you only find your own message.

How do you use it?

You use it by passing the original error as the cause of the new error, then reading it from err.cause wherever you catch it.

async function saveOrder(order) {
  try {
    await db.insert(order);
  } catch (err) {
    throw new Error("Saving the order failed.", { cause: err });
  }
}

try {
  await saveOrder(order);
} catch (err) {
  console.error(err.message);        // Saving the order failed.
  console.error(err.cause?.message); // the database error itself
}

Now the message speaks your app's language, and the reason stays with it all the way down. The same page shows this shape in a database example that throws a new error with the original attached.

When do you put data instead of an error?

You put data in cause when the code that catches the error needs to decide what to do by its type, not read a sentence.

MDN explains that error messages are written for people, and their wording can change and break any code that parses them, so you can put structured data in cause for code to read.

throw new Error("Payment failed.", {
  cause: { code: "card_declined", orderId },
});

And since the value can be of any type, the page warns: do not assume err.cause is an Error. Check its type before you read from it. If you need to group several unrelated errors, that is the job of AggregateError.

Where do you start now?

Every catch that throws a new error should carry the original with it. Search your project for throw new Error inside a catch, and add { cause: err } to each one.

If you are tidying up how you handle errors, see also how to hide the stack trace from users, how Promise.try collects errors, and time limits for fetch requests. What was the last error in your logs that came without its reason?

FAQ

Does cause have to be an Error object?

No. MDN says its value can be of any type, so when you read it, do not assume it is an Error. Check its type before you read a message from it.

What is the difference between cause and AggregateError?

cause is for a single failing site, and the new error only adds context. AggregateError is for a collection of unrelated errors that happened in the same operation.

Why don't I see cause when I loop over the error's properties?

Because MDN says it is not enumerable. Read it by name, err.cause, or log it on its own.

Share

More articles