Docs
Functions

defineErrorMap

Declare a reusable, typed map of error codes to share across procedures and middleware.

defineErrorMap captures an object of error codes with their literal types preserved, so you declare a set of errors once and pass it to a procedure's errors option, reusing it across the procedures and middleware that share those codes. It returns the map unchanged. Its only job is to infer precise types.

Parameters

defineErrorMap(map)

map

An object keyed by error code: your own code (e.g. POST_NOT_FOUND) or a common HTTP code you want to override. Each value is an ErrorDefinition.

Common codes

Keys may be any string, or one of the built-in HTTP codes below. Listing a common code overrides its default status/message. Every common code is throwable from a handler whether or not you list it.

CodeStatusMessage
BAD_REQUEST400Bad Request
UNAUTHORIZED401Unauthorized
FORBIDDEN403Forbidden
NOT_FOUND404Not Found
METHOD_NOT_SUPPORTED405Method Not Supported
NOT_ACCEPTABLE406Not Acceptable
TIMEOUT408Request Timeout
CONFLICT409Conflict
PRECONDITION_FAILED412Precondition Failed
PAYLOAD_TOO_LARGE413Payload Too Large
UNSUPPORTED_MEDIA_TYPE415Unsupported Media Type
UNPROCESSABLE_CONTENT422Unprocessable Content
TOO_MANY_REQUESTS429Too Many Requests
CLIENT_CLOSED_REQUEST499Client Closed Request
INTERNAL_SERVER_ERROR500Internal Server Error
NOT_IMPLEMENTED501Not Implemented
BAD_GATEWAY502Bad Gateway
SERVICE_UNAVAILABLE503Service Unavailable
GATEWAY_TIMEOUT504Gateway Timeout
UNEXPECTED_ERROR500An unexpected error occurred

Returns

The same object, typed as const. Assign it to a constant and pass it to a procedure's errors option, and derive its type with typeof when you need to refer to it. At runtime Kizlo turns it into the callable errors map your handler receives (see createThrowableErrorMap).

Examples

Define a map once, including a typed data payload and an override of a built-in error's copy:

src/lib/kizlo/server/post/error.ts
import { defineErrorMap } from "kizlo"
import { z } from "zod"

export const POST_ERRORS = defineErrorMap({
  POST_NOT_FOUND: { status: 404, message: "Post not found" },
  FORBIDDEN: { message: "You can't edit this post" }, // override a common error's message
  POST_RATE_LIMITED: { status: 429, data: z.object({ retryAfter: z.number() }) }, // typed payload
})

Pass it to every procedure that shares those codes:

createProcedure(
  { scope: "api", method: "GET", path: "/posts/{id}", /* …schemas… */ errors: POST_ERRORS },
  async ({ errors }) => {
    throw errors.POST_NOT_FOUND()
    // throw errors.POST_RATE_LIMITED({ data: { retryAfter: 30 } }) // data is required and typed
  },
)

On this page