Skip to content

errWithCause only serializes Error objects #158

@darcyrush

Description

@darcyrush

Javascript can throw anything, not just Error objects. This includes primitives like strings and numbers;

try {
  throw 42; // completely valid
} catch (e) {
  throw new Error("Nested error", { cause: e });
}

The bundled lib.es2022.error.d.ts TypeScript typings indirectly hints at this;

interface Error {
    cause?: unknown;
}

As such, I believe this is unexpected;

const serialize = require("pino-std-serializers").errWithCause;
const serialized = serialize(new Error("Example", { cause: 42 }));
console.log(serialized.cause); // undefined

I would expect the cause to be populated with 42. Likewise I would expect it to be populated if a string was thrown, or whatever else is legal to be thrown in JavaScript, including objects that don't extend the JS Error class. Instead, the cause is simply lost.

This example may seem like a contrived edge case, but I have come across libraries that throw their own "Error" objects, that do not extend from the native JS Error class,

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions