API Reference / @evolu/common / Type / createFormatTypeError

Function: createFormatTypeError()

function createFormatTypeError<ExtraErrors>(extraFormatter?): TypeErrorFormatter<TypeErrors<ExtraErrors>>;

Defined in: packages/common/src/Type.ts:3875

Creates a unified error formatter that handles both Evolu Type's built-in TypeErrors and custom errors. It also lets us override the default formatting for specific errors.

If you prefer not to reuse any built-in error formatters, you can write your own formatTypeError function from scratch.

Examples

const formatError = createFormatTypeError();
console.log(formatError({ type: "String", value: 42 }));
// "A value 42 is not a string."

A custom formatTypeError function:

type AppErrors =
  | ValidMutationSizeError
  | StringError
  | MinLengthError
  | MaxLengthError
  | NullError
  | IdError
  | TrimmedError
  | MnemonicError
  | LiteralError
  // Composite errors
  | ObjectError<Record<string, AppErrors>>
  | UnionError<AppErrors>;

const formatTypeError: TypeErrorFormatter<AppErrors> = (error) => {
  // In the real code, we would use the createTypeErrorFormatter helper
  // that safely stringifies error value.
  switch (error.type) {
    case "Id":
      return `Invalid Id on table: ${error.table}.`;
    case "MaxLength":
      return `Max length is ${error.max}.`;
    case "MinLength":
      return `Min length is ${error.min}.`;
    case "Mnemonic":
      return `Invalid mnemonic: ${String(error.value)}`;
    case "Null":
      return `Not null`;
    case "String":
      // We can reuse existing formatter.
      return formatStringError(error);
    case "Trimmed":
      return "Value is not trimmed.";
    case "ValidMutationSize":
      return "A developer made an error, this should not happen.";
    case "Literal":
      return formatLiteralError(error);
    // Composite Types
    case "Union":
      return `Union errors: ${error.errors.map(formatTypeError).join(", ")}`;
    case "Object": {
      if (
        error.reason.kind === "ExtraKeys" ||
        error.reason.kind === "NotObject"
      )
        return "A developer made an error, this should not happen.";
      const firstError = Object.values(error.reason.errors).find(
        (e) => e !== undefined,
      )!;
      return formatTypeError(firstError);
    }
  }
};

Type Parameters

Type ParameterDefault type
ExtraErrors extends TypeError<Capitalize<string>>never

Parameters

ParameterType
extraFormatter?TypeErrorFormatter<ExtraErrors>

Returns

TypeErrorFormatter<TypeErrors<ExtraErrors>>

Was this page helpful?