Skip to content

Handling errors of type other than Error #22

@simas-b

Description

@simas-b

Hello,

The handler expects err argument to be of type Error, while in theory you can throw anything in JS - string, number, undefined etc. Universal error handler should expect type of err: unknown.

If the package is still maintained I could work on PR that checks for type of err we get and if it's not Error, construct an actual Error instance before handling it further.

If the package is still maintained, I could work on PR to address this. What do you think?

The way I do it in my current JSON error handling middleware is by using these functions:

function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
  return (
    typeof error === "object" &&
    error !== null &&
    "message" in error &&
    typeof (error as Record<string, unknown>).message === "string"
  );
}

function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {
  if (isErrorWithMessage(maybeError)) return maybeError;

  try {
    return new Error(JSON.stringify(maybeError));
  } catch {
    /**
     * fallback in case there's an error stringifying the maybeError like with
     * circular references or bigint values for example.
     */
    return new Error(String(maybeError));
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions