Merging stack traces in rethrown errors

Here is a lightweight alternative to VError: rerror (I’m the author)

The idea is the same: Wrapping errors in errors. However it is much simpler. It has less features, but also works in the browser. It also takes into account that creating stack traces is expensive. Instead of creating stack traces and appending them to a string it creates a stack of errors internally and only creates the big stack trace if you need it (use the getter).

Example

function fail() {
  throw new RError({
    name: 'BAR',
    message: 'I messed up.'
  })
}

function failFurther() {
  try {
    fail()
  } catch (err) {
    throw new RError({
      name: 'FOO',
      message: 'Something went wrong.',
      cause: err
    })
  }
}

try {
  failFurther()
} catch (err) {
  console.error(err.why)
  console.error(err.stacks)
}

Output

FOO: Something went wrong. <- BAR: I messed up.
Error
    at failFurther (/Users/boris/Workspace/playground/es5/index.js:98:11)
    at Object.<anonymous> (/Users/boris/Workspace/playground/es5/index.js:107:3)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
<- Error
    at fail (/Users/boris/Workspace/playground/es5/index.js:88:9)
    at failFurther (/Users/boris/Workspace/playground/es5/index.js:96:5)
    at Object.<anonymous> (/Users/boris/Workspace/playground/es5/index.js:107:3)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)

A recommended read: https://www.joyent.com/node-js/production/design/errors


As far as I know, there is no built-in way to handle nested errors in Node.js. The only thing I can recommend you is to use the VError library. It is really useful when dealing with advanced error handling.

You can use fullStack to combine stack traces of many errors:

var err1 = new VError('something bad happened');
var err2 = new VError(err1, 'something really bad happened here');

console.log(VError.fullStack(err2));