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.
| Code | Status | Message |
|---|---|---|
BAD_REQUEST | 400 | Bad Request |
UNAUTHORIZED | 401 | Unauthorized |
FORBIDDEN | 403 | Forbidden |
NOT_FOUND | 404 | Not Found |
METHOD_NOT_SUPPORTED | 405 | Method Not Supported |
NOT_ACCEPTABLE | 406 | Not Acceptable |
TIMEOUT | 408 | Request Timeout |
CONFLICT | 409 | Conflict |
PRECONDITION_FAILED | 412 | Precondition Failed |
PAYLOAD_TOO_LARGE | 413 | Payload Too Large |
UNSUPPORTED_MEDIA_TYPE | 415 | Unsupported Media Type |
UNPROCESSABLE_CONTENT | 422 | Unprocessable Content |
TOO_MANY_REQUESTS | 429 | Too Many Requests |
CLIENT_CLOSED_REQUEST | 499 | Client Closed Request |
INTERNAL_SERVER_ERROR | 500 | Internal Server Error |
NOT_IMPLEMENTED | 501 | Not Implemented |
BAD_GATEWAY | 502 | Bad Gateway |
SERVICE_UNAVAILABLE | 503 | Service Unavailable |
GATEWAY_TIMEOUT | 504 | Gateway Timeout |
UNEXPECTED_ERROR | 500 | An 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:
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
},
)