Serialization & Transport
Send typed errors over HTTP and rebuild them with full types.
A NiceError turns into plain JSON, travels over the network, and is rebuilt on the other side. Its ids, context, and HTTP status all arrive intact.
Serializing
Section titled “Serializing”const json = error.toJsonObject(); // plain JSON object: everything, stack includedconst str = error.toJsonString(); // the same, as a JSON stringconst response = error.toHttpResponse(); // the same, as a Response with the error's HTTP statusWhich form to send
Section titled “Which form to send”toJsonObject() writes everything the error holds, and that includes its stack and its origin
error: file paths, and whatever a database or a library put in a message. That is right for your
own log. It is not what to hand a browser. There are three forms, by who reads them:
| Who reads it | Send | What it holds |
|---|---|---|
| Your own log or store | error.toJsonObject() | Everything |
| Your own code on the other side of a boundary you own, such as a framework’s server-to-browser hand-off | error.toJsonObject({ stack: false, originError: "summary" }) | Ids, context and message. No stack. The origin error cut to its name and message |
| Anyone else: a browser, a public API | error.toWireJsonObject() | Ids, context and message. No stack, no origin error. An error that isUnhandled is replaced whole by the sealed failure |
The sealed failure is err_cast_not_nice, id unhandled, status 500, one fixed sentence. A cast’s
message and context are the thrown value itself, so nothing of it is kept. @nice-code/action and
@nice-code/realm send the wire form for you. A response you build yourself is yours to choose:
import { castNiceError } from "@nice-code/error";
function toResponse(thrown: unknown): Response { const wire = castNiceError(thrown).toWireJsonObject(); // The status of what is sent: 500 for a sealed failure, whatever the thrown value was. return Response.json(wire, { status: wire.httpStatusCode });}toJsonObject takes stack: false to leave the stack out, and originError as "full" (the
default), "summary" or "omit".
sealedFailure() returns the sealed failure as an error, for code that has caught something, logged
it, and wants to answer with nothing more:
import { sealedFailure } from "@nice-code/error";
try { await chargeCard(order);} catch (caught) { log.error(caught); throw sealedFailure();}Receiving — castNiceError
Section titled “Receiving — castNiceError”On the receiving side, castNiceError turns any caught value into a NiceError:
import { castNiceError } from "@nice-code/error";
const caught = castNiceError(unknownValue); // always returns a NiceError
if (err_auth.isExact(caught)) { const hydrated = err_auth.hydrate(caught); // deserialize context const { username } = hydrated.getContext("invalid_credentials");}castNiceError copes with anything you hand it and never throws. That includes a NiceError, a JSON object, a plain Error, an error-like object, null/undefined, even a primitive. A JSON object that only resembles a NiceError, with no ids list for example, is treated as an error-like object and comes back with isUnhandled === true.
Reading it back — niceErrorFromJson
Section titled “Reading it back — niceErrorFromJson”niceErrorFromJson takes what a serializer produced, as a JSON string or as an object already
parsed, and returns a NiceError. Like castNiceError, it never throws: a string that is not JSON,
or JSON that is not an error, comes back with isUnhandled === true.
import { niceErrorFromJson } from "@nice-code/error";
const error = niceErrorFromJson(serialized); // a string or an object
if (err_auth.isExact(error)) { const { username } = err_auth.hydrate(error).getContext("invalid_credentials");}Is it a NiceError? — isNiceError
Section titled “Is it a NiceError? — isNiceError”import { isNiceError } from "@nice-code/error";
if (isNiceError(caught)) { caught.getIds();}Prefer isNiceError to instanceof NiceError. instanceof knows only the class your file imported, and an install that holds two copies of @nice-code/error has two such classes: an error thrown through the other copy fails instanceof and passes isNiceError. The domain guards (isExact, isThisOrChild, isParentOf) recognize it the same way, and castNiceError and hydrate rebuild it as your copy’s own, with its ids, context and message intact.
Two copies is still an install to repair. The package warns once as it loads when another version of itself is already in the process. → Production Posture
One-step — castAndHydrate
Section titled “One-step — castAndHydrate”When you have a specific domain in mind, castAndHydrate casts, checks the domain, and hydrates in a single call:
import { castAndHydrate, matchFirst } from "@nice-code/error";
const error = castAndHydrate(unknownValue, err_auth);// → a hydrated NiceError when it belongs to err_auth, otherwise the raw cast NiceError
if (err_auth.isExact(error)) { const message = matchFirst(error, { invalid_credentials: ({ username }) => `Wrong password for ${username}`, account_locked: () => "Account locked", });}Why hydration matters
Section titled “Why hydration matters”Only JSON travels over the network. So if an id’s context held a Date, an Error, or anything with a custom pack/unpack pair, hydration is the step that turns the JSON form back into the real typed value. Always hydrate (or castAndHydrate) before reading context that just came in from somewhere else.
A full round trip
Section titled “A full round trip”// Server: the wire form, with the status of what is sentconst wire = error.toWireJsonObject();return Response.json(wire, { status: wire.httpStatusCode });
// Clientconst caught = castNiceError(await res.json());if (err_auth.isExact(caught)) { const hydrated = err_auth.hydrate(caught); // hydrated.getContext(...) is now fully typed and real}