Server Error Mapping
Auto-map Prisma, ZenStack, and Zod server errors to form fields
Overview
mapServerErrors() automatically detects the error format and maps it to form fields. No manual switch/case needed.
import { applyServerErrors, mapServerErrors } from '@letar/forms'
;<Form
schema={UserSchema}
onSubmit={async ({ value }) => {
try {
await createUser(value)
} catch (error) {
const mapped = mapServerErrors(error, {
fieldMap: {
email: { field: 'email', message: 'This email is already registered' },
},
})
applyServerErrors(form, mapped)
}
}}
>
<Form.Field.String name="email" />
<Form.Errors />
<Form.Button.Submit>Create</Form.Button.Submit>
</Form>Full example
The complete sandbox example, read directly from the form-develop-app source at build time.
'use client'
import { Box, Code, Heading, HStack, Text, VStack } from '@chakra-ui/react'
import { actionFailure, Form, mapServerErrors, useFormRef, useFormServerAction } from '@letar/forms'
import { useState } from 'react'
import { z } from 'zod/v4'
import { DemoPageLayout } from '../_components'
import { toaster } from '../_components/toaster'
// Имитация серверных ошибок разных типов
const ERROR_EXAMPLES = {
'Prisma P2002 (unique)': { code: 'P2002', message: 'Unique constraint failed', meta: { target: ['email'] } },
'Prisma P2002 (composite)': { code: 'P2002', message: 'Unique', meta: { target: ['organizationId', 'name'] } },
'Prisma P2003 (FK)': { code: 'P2003', message: 'FK failed', meta: { field_name: 'categoryId' } },
'Prisma P2025 (not found)': { code: 'P2025', message: 'Record not found' },
'ZenStack policy': { reason: 'rejected-by-policy' as const },
'ZenStack cannot-read-back': {
reason: 'rejected-by-policy' as const,
rejectedByPolicyReason: 'cannot-read-back' as const,
},
'ZenStack db-query + P2002': { reason: 'db-query-error' as const, code: 'P2002', meta: { target: ['email'] } },
'Zod flatten': {
formErrors: ['Пароли не совпадают'],
fieldErrors: { email: ['Некорректный email'], password: ['Минимум 8 символов'] },
},
'ActionResult string': { success: false as const, error: 'Пользователь уже существует' },
'ActionResult nested': {
success: false as const,
error: { formErrors: [], fieldErrors: { name: ['Обязательное поле'] } },
},
'ActionFailure (поле)': { success: false as const, error: 'Такой адрес уже занят', field: 'slug' },
'Error объект': new Error('Что-то пошло не так'),
null: null,
} as const
// --- Живой пример useFormServerAction ---
const SignupSchema = z.object({
email: z.string().min(1).meta({ ui: { title: 'Email' } }),
}).strip()
type SignupData = z.infer<typeof SignupSchema>
/** Имитация server action — «занятый» email ведёт себя как Prisma P2002 на уникальном поле. */
async function fakeCreateUser(data: SignupData): Promise<{ id: string }> {
await new Promise((resolve) => setTimeout(resolve, 600))
if (data.email === 'taken@example.com') {
throw { code: 'P2002', message: 'Unique constraint failed', meta: { target: ['email'] } }
}
return { id: crypto.randomUUID() }
}
function UseFormServerActionDemo() {
const formRef = useFormRef()
const { run, pending } = useFormServerAction(formRef, {
fieldMap: { email: { field: 'email', message: 'Этот email уже зарегистрирован' } },
toaster,
successMessage: 'Пользователь создан',
})
return (
<VStack align="stretch" gap={3} maxW="sm">
<Text fontSize="sm" color="fg.muted">
Введите{' '}
<Code>taken@example.com</Code>, чтобы увидеть маппинг ошибки на поле + toast. Любой другой email — успех.
</Text>
<Form
schema={SignupSchema}
initialValue={{ email: '' }}
formRef={formRef}
onSubmit={async (data) => {
await run(() => fakeCreateUser(data))
}}
>
<Form.Errors />
<Form.Field.String name="email" />
<Form.Button.Submit loadingText="Отправка...">Создать</Form.Button.Submit>
</Form>
<Text fontSize="xs" color="fg.muted">
pending: <Code>{String(pending)}</Code>
</Text>
</VStack>
)
}
// --- Отказ Server Action значением (ActionFailure) ---
const CategorySchema = z.object({
slug: z.string().min(1).meta({ ui: { title: 'Адрес (slug)' } }),
}).strip()
type CategoryData = z.infer<typeof CategorySchema>
/**
* Имитация server action, которая ВОЗВРАЩАЕТ отказ значением (в production Next.js стирает текст
* брошенной ошибки). На сервере это делает `catchActionFailure` из `@letar/forms/server-errors`.
*/
async function fakeCreateCategory(data: CategoryData) {
await new Promise((resolve) => setTimeout(resolve, 600))
if (data.slug === 'taken') {
return actionFailure('Такой адрес уже занят — задайте другой', 'slug')
}
if (data.slug === 'locked') {
return actionFailure('Категорию нельзя изменять: она используется в заказах')
}
return { id: crypto.randomUUID() }
}
function ActionFailureDemo() {
const formRef = useFormRef()
const { run, pending } = useFormServerAction(formRef, { toaster, successMessage: 'Категория создана' })
return (
<VStack align="stretch" gap={3} maxW="sm">
<Text fontSize="sm" color="fg.muted">
<Code>taken</Code> — отказ с полем (под полем и в общем блоке), <Code>locked</Code>{' '}
— отказ без поля (только общий блок). Любой другой адрес — успех. Отказ приходит значением, а <Code>run</Code>
{' '}
сам бросает его как <Code>ActionFailureError</Code>.
</Text>
<Form
schema={CategorySchema}
initialValue={{ slug: '' }}
formRef={formRef}
onSubmit={async (data) => {
await run(() => fakeCreateCategory(data))
}}
>
<Form.Errors />
<Form.Field.String name="slug" />
<Form.Button.Submit loadingText="Отправка...">Создать</Form.Button.Submit>
</Form>
<Text fontSize="xs" color="fg.muted">
pending: <Code>{String(pending)}</Code>
</Text>
</VStack>
)
}
export default function ServerErrorsDemoPage() {
const [selectedError, setSelectedError] = useState<string>('Prisma P2002 (unique)')
const error = ERROR_EXAMPLES[selectedError as keyof typeof ERROR_EXAMPLES]
const mapped = mapServerErrors(error, {
fieldMap: {
email: { field: 'email', message: 'Этот email уже зарегистрирован' },
organizationId_name: { field: 'name', message: 'Такое название уже занято в организации' },
},
})
return (
<DemoPageLayout title="mapServerErrors()" description="Автоматический маппинг серверных ошибок на поля формы">
<VStack gap={8} align="stretch">
{/* Выбор типа ошибки */}
<Box>
<Heading size="md" mb={3}>
Тип серверной ошибки
</Heading>
<HStack gap={2} flexWrap="wrap">
{Object.keys(ERROR_EXAMPLES).map((key) => (
<Box
key={key}
as="button"
px={3}
py={1.5}
fontSize="sm"
borderRadius="md"
bg={selectedError === key ? 'blue.600' : 'gray.700'}
color="white"
cursor="pointer"
onClick={() => setSelectedError(key)}
_hover={{ bg: selectedError === key ? 'blue.500' : 'gray.600' }}
>
{key}
</Box>
))}
</HStack>
</Box>
{/* Входная ошибка */}
<Box>
<Heading size="sm" mb={2} color="red.400">
Входные данные (error)
</Heading>
<Code display="block" whiteSpace="pre-wrap" fontSize="xs" p={4} borderRadius="md">
{JSON.stringify(error, null, 2)}
</Code>
</Box>
{/* Результат маппинга */}
<Box>
<Heading size="sm" mb={2} color="green.400">
Результат mapServerErrors()
</Heading>
<Code display="block" whiteSpace="pre-wrap" fontSize="xs" p={4} borderRadius="md">
{JSON.stringify(mapped, null, 2)}
</Code>
</Box>
{/* Fieldmap конфиг */}
<Box>
<Heading size="sm" mb={2} color="blue.400">
Конфигурация fieldMap
</Heading>
<Code display="block" whiteSpace="pre-wrap" fontSize="xs" p={4} borderRadius="md">
{`fieldMap: {
email: { field: 'email', message: 'Этот email уже зарегистрирован' },
organizationId_name: { field: 'name', message: 'Такое название уже занято' },
}`}
</Code>
</Box>
{/* Пример использования */}
<Box>
<Heading size="md" mb={3}>
Пример использования в onSubmit
</Heading>
<Code display="block" whiteSpace="pre" fontSize="xs" p={4} borderRadius="md">
{`import { mapServerErrors, applyServerErrors } from '@letar/forms'
<Form schema={UserSchema} onSubmit={async ({ value }) => {
try {
await createUser(value)
} catch (error) {
// Автодетект: Prisma P2002 → поле email
const mapped = mapServerErrors(error, {
fieldMap: {
email: { field: 'email', message: 'Этот email занят' },
},
})
// Вариант 1: применить к форме
applyServerErrors(form, mapped)
// Вариант 2: показать в toast
if (mapped.formErrors.length) {
toaster.error({ title: mapped.formErrors[0] })
}
}
}}>
<Form.Field.String name="email" />
<Form.Errors /> {/* Покажет ошибки из applyServerErrors */}
</Form>`}
</Code>
</Box>
{/* useFormServerAction — та же связка в один вызов */}
<Box>
<Heading size="md" mb={3}>
useFormServerAction — та же связка в один вызов
</Heading>
<Text fontSize="sm" color="fg.muted" mb={3}>
Обёртка над примером выше: `formRef` + `mapServerErrors`/`applyServerErrors` + pending-состояние +
опциональный toaster в одном хуке, без `middleware.onError`.
</Text>
<UseFormServerActionDemo />
</Box>
{/* Отказ значением */}
<Box>
<Heading size="md" mb={3}>
Отказ Server Action значением — ActionFailure
</Heading>
<Text fontSize="sm" color="fg.muted" mb={3}>
В production Next.js стирает текст ошибки, брошенной из Server Action. Ожидаемый отказ сервер возвращает
значением (<Code>actionFailure</Code> / <Code>catchActionFailure</Code>), а форма бросает его обратно.
</Text>
<ActionFailureDemo />
</Box>
{/* Поддерживаемые форматы */}
<Box>
<Heading size="md" mb={3}>
Поддерживаемые форматы
</Heading>
<VStack align="start" gap={2} fontSize="sm">
<Text>
<strong>Prisma P2002</strong> — unique constraint → маппинг meta.target на поле
</Text>
<Text>
<strong>Prisma P2003</strong> — foreign key → маппинг meta.field_name
</Text>
<Text>
<strong>Prisma P2025</strong> — not found → глобальная ошибка
</Text>
<Text>
<strong>Prisma P2014</strong> — relation violation → "есть связанные записи"
</Text>
<Text>
<strong>ZenStack policy</strong> — rejected-by-policy → "Нет доступа"
</Text>
<Text>
<strong>ZenStack db-query</strong> — оборачивает Prisma, автодетект кода
</Text>
<Text>
<strong>Zod flatten</strong> — {'{ fieldErrors, formErrors }'} → прямой маппинг
</Text>
<Text>
<strong>ActionResult</strong> — {'{ success: false, error }'} → строка или nested
</Text>
<Text>
<strong>ActionFailure</strong> — {'{ success: false, error, field? }'} → под поле и в общий блок
</Text>
<Text>
<strong>Error с .info</strong> — ZenStack стиль (.info.reason)
</Text>
</VStack>
</Box>
</VStack>
</DemoPageLayout>
)
}shadcn-вариант этого примера ещё не готов.
Vue-пример для этого поля появится позже.
Angular-пример для этого поля появится позже.
With the declarative <Form>
The example above uses the low-level useAppForm hook, where form is available directly from closure. The declarative wrapper (createForm() → <Form onSubmit={(data) => ...}>) is different: its onSubmit receives only data, no form instance — error handling instead goes through middleware.onError, which receives whatever onSubmit/the Server Action threw (FormSimple catches the exception and calls middleware.onError, see libs/forms/src/lib/declarative/form-root/form-simple.tsx).
To call mapServerErrors/applyServerErrors here, get the form instance via useFormRef():
import { applyServerErrors, mapServerErrors, useFormRef } from '@letar/forms'
function MaterialForm() {
const formRef = useFormRef()
async function handleSubmit(data: MaterialFormData) {
// The Server Action just throws (Prisma/ZenStack/Error) — no manual wrapping needed
await createMaterial(data)
}
return (
<Form
schema={MaterialSchema}
initialValue={initialValue}
onSubmit={handleSubmit}
formRef={formRef}
middleware={{
onError: (error) => {
const mapped = mapServerErrors(error, {
fieldMap: { sku: { field: 'sku', message: 'This SKU is already in use' } },
})
if (formRef.current) {
applyServerErrors(formRef.current, mapped)
}
},
}}
>
<Form.Errors />
<Form.Field.String name="sku" />
<Form.Button.Submit>Save</Form.Button.Submit>
</Form>
)
}Key points:
formRefis passed to<Form>and used insidemiddleware.onError— without it,applyServerErrorshas nothing to apply errors to.- The Server Action called from
onSubmitshouldn't catch and wrap the error itself —mapServerErrorsparses raw Prisma/ZenStack/Zod exceptions directly. - Don't forget
<Form.Errors />in JSX, orformErrors(e.g.P2025/rejected-by-policy) get applied but never render. - Working example:
apps/domwellbes/src/app/(admin)/admin/materials/_components/material-form.tsx.
useFormServerAction — the same wiring in one call
The sections above give full control over formRef + middleware.onError +
mapServerErrors/applyServerErrors — useful when error handling differs by error type. For the
typical case (just apply the error to fields + show pending + an optional toast),
useFormServerAction (@letar/forms-react) collapses this ceremony into one hook:
import { Form, useFormRef, useFormServerAction } from '@letar/forms'
function SignupForm() {
const formRef = useFormRef()
const { run, pending } = useFormServerAction(formRef, {
fieldMap: { email: { field: 'email', message: 'This email is already registered' } },
toaster,
successMessage: 'User created',
})
return (
<Form schema={SignupSchema} initialValue={{ email: '' }} formRef={formRef}
onSubmit={async (data) => {
await run(() => createUser(data))
}}
>
<Form.Errors />
<Form.Field.String name="email" />
<Form.Button.Submit loadingText="Submitting...">Create</Form.Button.Submit>
</Form>
)
}run(action, onSuccess?)callsaction; on error it appliesmapServerErrors/applyServerErrorsand shows the toast, then rethrows the original error — this is required, not cosmetic: ifrunswallowed the error,<Form>would treat the submit as successful and its post-submitreset()would wipe the field errors just applied before the user got to see them. You still don't need your owntry/catchinonSubmit—<Form>catches the exception fromonSubmitin the same place it already catchesthrowfrommiddleware.onError.- On error — the same
mapServerErrors+applyServerErrors(formRef.current, mapped)as above, plustoaster.create({ type: 'error', ... })iftoasteris passed (the title comes fromformErrors, falling back to the firstfieldErrorsmessage, thendefaultMessage). - On success — an optional
toaster.create({ type: 'success', title: successMessage })and a call toonSuccess?.(result)with whateveractionreturned. pendingis a boolean flag for the duration ofaction, for a custom indicator next to<Form.Button.Submit loadingText="...">.- The low-level path (
middleware.onErrorfrom the section above) stays fully supported — use it when error handling needs to differ by error type (e.g. suppress the toast for some errors).
Rejecting a Server Action with a value — ActionFailure
⚠️ In production Next.js strips the text of any error thrown from a Server Action — the client
sees "Minified React error" (code 441) instead of the reason. So an expected failure (a business
rule, a duplicate of a unique value) is returned as a value, and the form turns it back into an
exception on the client — a client-side throw is not stripped. Real faults are still thrown: their
text is not for the user and belongs in the logs and error tracker.
Server (import from @letar/forms/server-errors — no React or Chakra):
'use server'
import { catchActionFailure, UserFacingError } from '@letar/forms/server-errors'
export async function createCategory(input: CategoryInput) {
return catchActionFailure(async () => {
if (await isNameReserved(input.name)) {
throw new UserFacingError('This name is reserved', 'name') // the field is optional
}
return db.category.create({ data: input, select: { id: true } })
}, {
// your own texts for a duplicate: the key is the field, or fields joined by "_"
uniqueMessages: { slug: 'This address is taken — pick another' },
locale: 'en', // language of the generic duplicate message
})
}catchActionFailure catches only UserFacingError and a unique violation (SQLSTATE 23505);
everything else is rethrown. To reject directly, return actionFailure('Cannot delete', 'id').
Client — two ways, both put the reason under the field and into <Form.Errors />:
// 1. useFormServerAction: run recognises the returned failure and throws ActionFailureError
const { run, pending } = useFormServerAction(formRef, { toaster })
await run(() => createCategory(data), () => router.push('/admin/categories/'))
// 2. Low-level: unwrapActionResult + middleware.onError
const { formRef, middleware } = useActionFormErrors()
<MyForm formRef={formRef} middleware={middleware}
onSubmit={async (data) => { unwrapActionResult(await createCategory(data)) }}>
<MyForm.Errors />onSuccess and the success toast are not called on a failure.
The marker. A failure is { success: false, error: string, field?: string }. The explicit
success: false matters: a successful result that happens to carry an error field
({ items, error: 'some rows skipped' }) is not treated as a failure. Build it with
actionFailure(error, field?), not by hand.
Which field a duplicate lands on. Prisma names the constraint <Table>_<field>_key. The field
is derived only when the name is unambiguous — three parts (MaterialCategory_slug_key →
slug). A composite key, a @@map("snake_case") table or a @map column has no field: _ cannot
tell them apart from an underscore inside a name, and an error under the wrong field is worse than
a generic message. The message then comes from uniqueMessages (matched against the tail of the
constraint name) or falls back to a generic one.
Supported Formats
| Format | Example | Result |
|---|---|---|
| Prisma P2002 | { code: 'P2002', meta: { target: ['email'] } } | fieldErrors: [{ field: 'email' }] |
| Prisma P2003 | { code: 'P2003', meta: { field_name: 'categoryId' } } | fieldErrors: [{ field: 'categoryId' }] |
| Prisma P2025 | { code: 'P2025' } | formErrors: ['Record not found'] |
| ZenStack policy | { reason: 'rejected-by-policy' } | formErrors: ['Access denied'] |
| ZenStack db-query | { reason: 'db-query-error', code: 'P2002', meta } | Delegates to Prisma parser |
| Zod flatten | { fieldErrors: { email: ['msg'] } } | Direct mapping |
| ActionResult | { success: false, error: 'msg' } | formErrors: ['msg'] |
| ActionFailure | { success: false, error: 'msg', field: 'slug' } | fieldErrors + formErrors |
API
mapServerErrors(error, config?)
const mapped = mapServerErrors(error, {
fieldMap: Record<string, { field: string; message: string }>,
format: 'auto' | 'prisma' | 'zenstack' | 'zod' | 'action-result',
locale: 'ru' | 'en',
defaultMessage: 'An error occurred',
})
// Returns: { fieldErrors: FieldError[], formErrors: string[] }applyServerErrors(form, mapped)
Applies errors to TanStack Form instance via form.setFieldMeta and form.setErrorMap.
fieldMap
Custom mapping for specific constraints:
{
// Single field unique constraint
email: { field: 'email', message: 'Email already registered' },
// Composite unique constraint (joined with _)
organizationId_name: { field: 'name', message: 'Name already taken' },
// Foreign key
categoryId: { field: 'categoryId', message: 'Select a valid category' },
}Import
// Main package
import { applyServerErrors, mapServerErrors } from '@letar/forms'
// Subpath (tree-shakeable)
import { mapServerErrors } from '@letar/forms/server-errors'
// Individual parsers
import { parsePrismaError, parseZenStackError } from '@letar/forms/server-errors'
// Rejecting a Server Action with a value (server — no React; client — hooks)
import { actionFailure, catchActionFailure, unwrapActionResult, UserFacingError } from '@letar/forms/server-errors'
import { useActionFormErrors, useFormServerAction } from '@letar/forms'