Crafting Error Trails In JavaScript

Crafting Error Trails In JavaScript

Using Error.prototype.cause to create better errors

Intercepting Errors and returning a new error with a more end-user-friendly message is a staple of JavaScript. However, this can cause us to lose steps in the stack trace or make debugging harder. Now thanks to Error.prototype.cause we can provide a more user-friendly message and keep a reference to the original error.

If you had a function connecting to a database or creating a table or document, you might have something like the code below. Wrapping the code in a try-catch, you might intercept the error to provide a more readable message to the API.

const db = {
    create: (user) => user
}

try {
  const user = {name: "Alexander", email: "some@email.com"}
  db.create(user)
} catch (err) {
  // Normally you would do something with the original error here, like add to a logger or bug tracker
  throw new Error("Could not add the new user",)
}

We can update this catch clause to use the new cause property in the error to keep track of the original error.

const db = {
    create: (user) => user
}

try {
  const user = {name: "Alexander", email: "some@email.com"}
  db.create(user)
} catch (err) {
  // Normally you would do something with the original error here, like add to a logger or bug tracker.\
  throw new Error("Could not add the new user", {cause: err})
}

Using the simple cause property, we have created a better error trail. All major browsers support the cause property, so you can use it today. Check the browser compatibility list for more info.

Did you find this article valuable?

Support Alexander Karan by becoming a sponsor. Any amount is appreciated!