Skip to main content

Instance rule

import trybox, { errorRule } from "trybox";

class HttpError extends Error {
  constructor(
    public status: number,
    public url: string,
    public body?: unknown
  ) {
    super("HTTP error");
  }
}

type HttpAppError = {
  code: "HTTP";
  message: string;
  status?: number;
  meta?: { url: string; body?: unknown };
  cause?: unknown;
};

const runner = trybox({
  rules: [
    errorRule.instance(HttpError).toError<HttpAppError>((e) => ({
      code: "HTTP",
      message: `Request failed (${e.status})`,
      status: e.status,
      meta: { url: e.url, body: e.body },
      cause: e,
    })),
  ],
});

Custom predicate

const runner2 = trybox({
  rules: [
    errorRule
      .when((x): x is { code: string } => typeof (x as any)?.code === "string")
      .toError((e) => ({
        code: (e as any).code,
        message: "Mapped",
      })),
  ],
});