CHAN.RUN

ensure

fault

fault()

function fault(
   target, 
   message, 
   options?): never;

Defined in: src/fault.ts

Throw a typed error — from a class or an inline string code.

fault(NotFoundError, "User not found");
fault("RATE_LIMITED", "Too many requests");

Parameters

ParameterType
targetstring | FaultErrorClass
messagestring
options?{ cause?: unknown; }
options.cause?unknown

Returns

never

Examples

import { fault, defineError } from "@chan.run/ensure";

const ValidationError = defineError("ValidationError");

function validateAge(age: number) {
  if (age < 0 || age > 150) {
    fault(ValidationError, `Invalid age: ${age}`);
  }
}
try {
  await stripe.charges.create(params);
} catch (err) {
  fault(PaymentFailedError, "Charge failed", { cause: err });
}
// No need to defineError — just use a string code.
// Same string always reuses the same error class internally.
fault("TODO", "Not implemented yet");
fault("UNAUTHORIZED", "You must be logged in");
function getStatusColor(status: "ok" | "warn" | "error"): string {
  switch (status) {
    case "ok": return "green";
    case "warn": return "yellow";
    case "error": return "red";
    default: fault("UNREACHABLE", `Unknown status: ${status}`);
  }
}
function requireAdmin(user: User) {
  if (user.role !== "admin") {
    fault(ForbiddenError, `User ${user.id} is not an admin`);
  }
}