Crafting Error Trails In JavaScript
Using Error.prototype.cause to create better errors

I have been a full-stack developer for twelve years and am currently part of the Cloud FinOps team at Atlassian. I previously ran an App development agency, managing various teams across design and development, leading web, backend and native mobile app developers in Australia and Europe. My strengths are system architecture design and communicating complicated tech to everyday people. Having helped scale tech at numerous startups, I am passionate about making a positive difference. When not working, you can find me writing tech articles and teaching Javascript and React at SheCodes, an initiative helping to get more women into tech. I regularly give talks on various topics, focusing on the impact the technology we build can have. I am devastated by the state of the world, love a good political rant and can often be swearing at no one in particular. I enjoy building things in JavaScript, Deno and Node.
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.




