Skip to content

feat: support a function as the error message#10

Merged
gmaclennan merged 3 commits into
mainfrom
feat/message-function
Jun 12, 2026
Merged

feat: support a function as the error message#10
gmaclennan merged 3 commits into
mainfrom
feat/message-function

Conversation

@gmaclennan

@gmaclennan gmaclennan commented Jun 11, 2026

Copy link
Copy Markdown
Member

Add support for passing a function as the message of an error definition. The function receives the (typed) params object and returns the message string. The params type for the constructor is inferred from the function's parameter, so you get full type-checking without a {param} template.

const TooMany = createErrorClass({
  code: "TOO_MANY_ITEMS",
  message: (params: { items: number[] }) =>
    `Found ${params.items.length} items, expected fewer`,
  status: 400,
});

new TooMany({ items: [1, 2, 3] });                  // ✅ params typed as { items: number[] }
new TooMany({ items: [1, 2, 3] }, { cause: err });  // ✅
new TooMany({ items: "nope" });                     // ❌ caught at compile time

A zero-argument function behaves like an error without template parameters:

const Unauthorized = createErrorClass({
  code: "UNAUTHORIZED",
  message: () => "Access denied",
  status: 401,
});

new Unauthorized();

Params type is inferred from the function's first parameter; whether params are required is driven by the function's
arity (number of arguments it expects - () => and (params = {}) => are no-param, (params) => requires params), keeping the runtime and type levels consistent.

Note: ErrorDefinition's default type parameter widens from string to string | MessageFn in this release. This is a public type change but is treated as non-breaking — ErrorDefinition is intended for internal use by this library, and external consumers reading def.message as a string would be unusual. Flagging in case anyone depends on it.

@gmaclennan gmaclennan self-assigned this Jun 11, 2026
@gmaclennan gmaclennan enabled auto-merge (squash) June 12, 2026 09:08
@gmaclennan gmaclennan merged commit fbd20e2 into main Jun 12, 2026
5 checks passed
@gmaclennan gmaclennan deleted the feat/message-function branch June 12, 2026 09:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant