Error Handling
Error handling
Actions return { data?, businessError?, serverError?, validationErrors? }. Keep the server error contract explicit.
Declared business failures
Declare expected public failure codes on the builder. Codes and messages are inferred in generated references and client result envelopes.
const action = createSafeActionClient()
.schema(profileSchema)
.errors({ EMAIL_TAKEN: 'This email is already registered' })
.action(({ parsedInput, fail }) => {
if (parsedInput.profile.email === 'taken@example.com') {
return fail('EMAIL_TAKEN', { validationErrors: { 'profile.email': ['Use a different email'] } })
}
return { accepted: true }
})
fail() returns never: it stops handler execution. Write return fail(...): TypeScript only narrows after a never call when the function has an explicit type annotation, which a destructured handler argument does not, so code after a bare fail(...) is not narrowed. The response is { businessError: { code, message }, validationErrors? }. Declarations are immutable builder configuration; provide messages intentionally suitable for the caller. Unknown errors continue through the existing server error mapper or generic fallback. Optional field errors use typed input paths, bounded to four traversal levels; existing returnValidationErrors() accepts string-keyed maps. Business failures are distinct from transport errors and do not refresh queries.
const result = await mutation.executeAsync(input)
if (result.businessError?.code === 'EMAIL_TAKEN') {
// Handle this expected outcome; result.businessError.message is public.
}
Existing ActionError, handleServerError, and returnValidationErrors continue to work.
From middleware
Middleware receives the same fail() helper, limited to codes declared by .errors() before that .use(). This lets a shared auth client return a typed code instead of a serverError string:
export const authActionClient = createSafeActionClient()
.errors({ UNAUTHORIZED: 'Please sign in to continue' })
.use(async ({ event, next, fail }) => {
const session = await getUserSession(event)
if (!session.user) return fail('UNAUTHORIZED')
return next({ ctx: { userId: session.user.id } })
})
Every action built from authActionClient includes UNAUTHORIZED in its inferred businessError type, alongside any codes the action adds with its own .errors(). A middleware failure stops the chain before validation and the handler run.
Typed serverError
handleServerError can return any type, such as { code, message }, but only unexpected exceptions pass through it. ActionError messages, 4xx H3 errors without a mapper, and client-side transport failures always produce a string serverError. For failures the caller should branch on, declare business errors instead of encoding codes in serverError, and use clientError for transport failures.
Intentional public errors
import { ActionError } from '#safe-action'
throw new ActionError('This operation is not allowed')
ActionError sends its message directly as serverError. Use it only for messages intended for the caller. It bypasses handleServerError; the mapper handles unexpected exceptions.
export const actionClient = createSafeActionClient({
handleServerError(error, { event, metadata }) {
console.error(`Action ${event.path} failed`, metadata, error)
return 'Something went wrong. Please try again.'
},
})
The second argument (0.8+) carries the H3 event, the action metadata, and the raw clientInput (unvalidated; avoid logging sensitive fields).
Without a mapper, unexpected errors return a generic message and are logged on the server with console.error. If the mapper itself throws, a generic fallback is returned and the mapper failure is logged. An output-schema validation failure is an unexpected server failure, not a client field error.
An H3 createError() with a 4xx status, such as createError({ statusCode: 401, statusMessage: 'Unauthorized' }) thrown from auth middleware, keeps its statusMessage as serverError when no mapper is configured. 5xx H3 errors are masked like any other unexpected error. With a mapper, every unexpected error, including H3 errors, goes through the mapper, which can read error.statusCode.
Field and root errors
Schema errors use dotted paths, including indices: profile.name, addresses.0.city. Issues without a path use _root. Malformed JSON bodies or GET input use _errors and does not run the action handler. useFormAction combines both root keys into rootErrors and omits them from fieldErrors.
Return business-rule errors from the handler with returnValidationErrors(). Despite its name, it throws a validation error and stops handler execution.
import { returnValidationErrors } from '#safe-action'
if (parsedInput.profile.name.toLowerCase() === 'admin') {
returnValidationErrors({ 'profile.name': ['This name is reserved'] })
}
The same field-error UI can display schema and business-rule errors. Array/path notation is available to Nuxt UI forms.
Transport failures
clientError requires nuxt-safe-action 0.8 or newer.Client network errors, non-2xx HTTP responses, external aborts, and timeouts resolve an envelope with a typed clientError and, for backwards compatibility, its message in serverError:
const { executeAsync, clientError } = useAction(saveProfile)
const result = await executeAsync(input)
if (result.clientError?.kind === 'aborted') return // user cancelled
if (result.clientError?.kind === 'http' && result.clientError.status === 403) {
// e.g. rejected by same-origin protection
}
clientError.kind is one of network, http (with status), timeout, aborted, invalid-response or invalid-reference. Prefer it over serverError for these cases: a custom TServerError type from handleServerError does not describe client-side failures. Explicit cancel()/reset() before a response arrives suppress that run's callbacks and state updates. Once a run has delivered onSuccess or onError, calling reset() from those callbacks clears state but still lets that run refresh its invalidate targets and call onSettled. Cancellation cannot roll back work already performed on the server. Errors are represented separately from successful data; do not infer success from data truthiness.
The result envelope is the application error contract. Ordinary validation/action failures are returned in the envelope; do not rely on distinct HTTP status codes for each application error.