DEV Community

Cover image for Pony Cause 1.0: Error Causes
Pelle Wessman
Pelle Wessman

Posted on

Pony Cause 1.0: Error Causes

Pony Cause is my new ponyfill and helpers for the new Error Cause tc39 proposal.

The ponyfill as well as the proposal aims to replace VError / NError with a standard mechanism for wrapping errors and improving error contexts.

How does it wrap errors?

The Error Cause proposals add a second argument to the Error constructor.

The new argument is a plain object with so far cause as its only defined key.

cause is intended to be the value of a caught error.

That way cause enables an Error of a higher level to reference one of a lower level error, adding context without sacrificing detail.

An example:

try {
  // ...
  throw new Error('ABC123 exception encountered in database "Foo"');
} catch (err) {
  throw new Error('Failed to save blog post', { cause: err })
}
Enter fullscreen mode Exit fullscreen mode

The Failed to save blog post message provides a higher level context, it tells us what has happened, it tells us the impact.

The inner ABC123 exception encountered in database "Foo" message tells us why this happened, it tells us the cause.

So why wrap errors?

In classic JavaScript it has been an either or – either getting to know the impact or the cause, but never both Error:s (unless one has logged them separately or have used VError / NError).

The impact and cause provides the most value when paired with the other, and that's what Error Cause enables and what Pony Cause is is a ponyfill for and provides helpers for.

What does pony-cause add?

Pony Cause is consist of two parts:

  1. A ponyfill in the shape of a ErrorWithCause class which mimics the new cause-supporting Error class.
  2. A couple of VError-inspired helpers for working with error causes, ensuring that the added context becomes actually useful. These helpers also supports VError style causes on top of the new error causes, enabling a smooth transition from one to the other.

Which helpers does it add?

Anything else I should know?

Pony Cause is written in JS, typed with JSDoc, validated with TypeScript and have .d.ts / .d.ts.map generated by TypeScript. In other words: 100% typed in true Types in JS spirit.

It's a CommonJS module rather than ESM, to maximise compatibility here and now, as that's the point of a ponyfill.

It's licensed under the 0BSD license, a BSD/MIT-style license with the requirement for attribution removed.

Will there be native support?

Yes, it's recently been implemented in all three major browsers and V8 shipped native support a bit over a month ago with eg. Node.js v16.9.0 and Deno v1.13 both having already shipped with that version of V8.

Though you still need a ponyfill or polyfill if you want to support older browsers or older Node.js versions.

Pony Cause also provides helpers which are useful no matter if you're using it with old environments or not it is a module that your toolbox needs 😉

Discussion (0)