Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Keep the original error with cause

Pass the caught error as cause when you rethrow so Node can show the original failure alongside your message.

Your catch block rethrows new Error('Cannot load config'), and the log now says nothing about why. The original error carried a code, a path and a stack. The rethrow threw all of it away.

Pass the original as cause

The Error constructor takes a second argument, an options object with a cause property. Put the caught error there and the new error keeps a reference to it.

import { readFile } from 'node:fs/promises'

class ConfigError extends Error {
  name = 'ConfigError'
}

async function loadConfig(path) {
  try {
    return JSON.parse(await readFile(path, 'utf8'))
  } catch (cause) {
    throw new ConfigError(`Cannot load config from ${path}`, { cause })
  }
}

try {
  await loadConfig('./missing.json')
} catch (err) {
  console.error(err)
}

ConfigError is the error the caller sees, with a message that names your domain, and err.cause is the ENOENT error from readFile.

What Node prints

console.error(err) shows both errors. The cause appears under the first one as [cause], with its own stack and its own properties.

ConfigError: Cannot load config from ./missing.json
    at loadConfig (file:///.../chain.mjs:11:11)
    at async file:///.../chain.mjs:22:3 {
  [cause]: Error: ENOENT: no such file or directory, open './missing.json'
      at async open (node:internal/fs/promises:636:25)
      at async readFile (node:internal/fs/promises:1235:14)
      at async loadConfig (file:///.../chain.mjs:9:23)
      at async file:///.../chain.mjs:22:3 {
    errno: -2,
    code: 'ENOENT',
    syscall: 'open',
    path: './missing.json'
  }
}

The readFile frames in the cause's stack show where the file system call failed. The outer stack shows where you wrapped it. Node also displays the cause for an uncaught exception.

Walk the chain

Code that needs the root problem can follow cause until it runs out. Call this in the same catch block. A cause may be any value. This helper follows Error objects and uses a set to stop if a cause points back to an error it has already seen.

function chain(err) {
  const out = []
  const seen = new Set()
  for (let e = err; e instanceof Error && !seen.has(e); e = e.cause) {
    seen.add(e)
    out.push(`${e.name}: ${e.message}`)
  }
  return out
}

console.log(chain(err))
// [
//   'ConfigError: Cannot load config from ./missing.json',
//   "Error: ENOENT: no such file or directory, open './missing.json'"
// ]
console.log(err.cause.code) // ENOENT

The array lists the wrapper first and the original last, and err.cause.code gives you ENOENT to branch on.

A logger that calls JSON.stringify(err) prints {"name":"ConfigError"} and drops the rest, because message, stack and cause are not enumerable. Hand the error object itself to console.error or to a logger that formats errors.

I wrap an error when the layer above should see my domain's name for the failure. I always pass the original as cause, so the log keeps the line where it failed.