Skip to content

Error Handling

Every action ends in one predictable result, so you can tell planned-for errors from real crashes.

Every action finishes with a clear, predictable outcome. It never rejects with a raw throw. Your handler can throw anything it likes: a declared NiceError, an undeclared one, or a plain Error. The runtime turns all of them into one typed result, so the place you call from always has the same shape to check.

When an action fails, there are two separate things you might want to know:

QuestionWhere to lookMeaning
Did this action say it could throw this?result.expected (on the result)You listed it with .throws(), so it’s a known, planned-for error.
Did something fail that nobody planned for?error.isUnhandled (on the error)In your own process: something threw that wasn’t a NiceError at all. From a server: the action failed and the server kept the detail.

expected depends on which action you called. The same NiceError can be expected for one action that declared it, and unexpected for another that didn’t. isUnhandled is a property of the error itself. It’s true for the generic wrapper castNiceError puts around a non-NiceError throw, and for the sealed failure a server sends in place of anything an action did not declare.

Get the outcome as a value and check it. No try/catch.

import { matchFirst } from "@nice-code/error";
const result = await act_user.action.getUser.request({ userId }).runToResult();
if (result.ok) {
use(result.output);
} else if (result.expected) {
// result.error is fully typed — it can only be one of this action's declared errors.
matchFirst(result.error, {
not_found: ({ userId }) => show404(userId),
forbidden: () => showForbidden(),
});
} else {
// This action didn't declare this one. Check the error's own flag if you care which kind it is:
if (result.error.isUnhandled) alertOncall(result.error); // it failed, and nobody said how
else report(result.error); // a real NiceError nobody declared
}

From a server, the last branch is rare. A server sends a NiceError an action did not declare as the sealed failure, so it lands in the branch above it. What still reaches the last branch is a NiceError thrown in your own process, one of the library’s own (such as action_not_served on a socket), and any NiceError from a server that set sealFailures: "unhandled".

The outcome is one of three shapes:

type TActionResultOutcome<OUT, DECLARED> =
| { ok: true; output: OUT }
| { ok: false; expected: true; error: DECLARED } // one of the errors this action declared
| { ok: false; expected: false; error: NiceError }; // anything else

expected is always worked out fresh against the receiver’s own definition. It’s never trusted from the wire, so an error that arrived over the network is sorted exactly the same way as one thrown locally.

A handler can throw anything, and what it throws often holds things a caller must not read: a SQL statement, a row, a file path, a stack. So a server sends a caller only what the action’s definition lists.

The failureWhat the caller is sent
An error the action declared with .throws()Whole: its domain, ids, message and context
The refusal of an input: err_nice_action, action_input_validation_failedThe same. Its message quotes the caller’s own value
Anything else: a thrown Error, string or object, a NiceError the action did not declare, an output the schema rejectsThe sealed failure

The sealed failure is one fixed error: err_cast_not_nice, id unhandled, isUnhandled: true, HTTP status 500, one fixed sentence and no context. It says that the server failed, and nothing else. No row of the table carries a stack or an originError.

So an error a client should read is an error the action declares. If a handler throws a NiceError the action does not list, the server writes a line the first time it happens:

[nice-action] act_user/getUser failed with err_billing/card_expired, which the action does not declare,
so its caller was sent the sealed failure. Declare it with .throws() to send it whole.

The server keeps the detail: its serve logger is handed the error as it was thrown, with the request’s cuid. Show the user that reference instead of the message, and a report can be matched to its log line:

const request = act_user.action.getUser.request({ userId });
const result = await request.runToResult();
if (!result.ok && result.error.isUnhandled) {
showError(`Something went wrong. Reference: ${request.context.cuid}`);
}

Over HTTP that string is the one in the server’s log. On a socket it is not: a socket’s default codec does not send the cuid, and each side keeps its own.

The table above is the default, "undeclared". sealFailures is an option wherever you serve: serveChannel, serveWorker, serveDurableObject.

sealFailuresWhat is sealed
"undeclared"Everything the action did not declare. The default
"unhandled"Only a thrown value that is not a NiceError. Every NiceError a handler throws is sent with its context, declared or not
"off"Nothing, and each failure is sent with its stack and origin error. For a developer’s machine only
serveChannel(appChannel, {
// …
sealFailures: isDev ? "off" : "undeclared",
});

A request can also be turned away before any action runs: an origin, a size, an action the server does not have. Those are not failed results and are not sealed. See What an endpoint refuses.

If you prefer runToOutput() (which throws on failure), use the action’s isExpectedError check to narrow a caught error:

import { castNiceError, matchFirst } from "@nice-code/error";
try {
const output = await act_user.action.getUser.request({ userId }).runToOutput();
} catch (e) {
if (act_user.action.getUser.isExpectedError(e)) {
// e is now narrowed to this action's declared errors
matchFirst(e, { not_found: ({ userId }) => show404(userId), forbidden: () => showForbidden() });
} else {
report(castNiceError(e).toStructuredLog());
}
}

The two questions above sort failures that came back from a handler. A call can also fail because no transport ever came up, so nothing reached a handler to succeed or throw. You get that as err_nice_transport with the id initialization_failed, and it carries the two things you need to act on it:

import { err_nice_transport, EWireConnectFailureKind } from "@nice-code/action";
if (err_nice_transport.isExact(e) && e.hasId("initialization_failed")) {
const { endpoint, kind } = e.getContext("initialization_failed");
if (kind === EWireConnectFailureKind.endpoint_answered_non_protocol) {
// Something answered, but it isn't the backend — wrong URL, or a proxy/WAF in the way.
reportMisroute(endpoint);
} else if (kind === EWireConnectFailureKind.endpoint_unreachable) {
showOfflineBanner(); // nothing there: server down, wrong port, firewall, offline
}
}

kind is a typed discriminator. Branch on it rather than matching the message text, which is the brittle habit it exists to replace. endpoint names the URL that transport actually dialed, so the error tells you where it happened.

If you’re holding a dial error from anywhere else in the stack, classifyConnectFailure(error) returns the same EWireConnectFailureKind for any error, or unknown when it can’t tell. Both it and the enum are re-exported from @nice-code/action, so an app using actions never needs to import @nice-code/wire directly:

import { classifyConnectFailure, EWireConnectFailureKind } from "@nice-code/action";
if (classifyConnectFailure(e) === EWireConnectFailureKind.endpoint_unreachable) retryLater();

Error Reference has the full table of kind values, what each means, and the first thing to check. The Connection covers the connection lifecycle these failures come from.

The browser devtools panel sorts each failed run by these same two questions. Based on result.expected, an error is labelled either Expected Error (declared) or Unexpected Error (undeclared / unhandled). Based on error.isUnhandled, an unexpected crash gets an extra unhandled badge, and so does a sealed failure. The distinction you check in code is the one you see in the timeline.