Skip to content

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.

const json = error.toJsonObject(); // plain JSON object: everything, stack included
const str = error.toJsonString(); // the same, as a JSON string
const response = error.toHttpResponse(); // the same, as a Response with the error's HTTP status

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 itSendWhat it holds
Your own log or storeerror.toJsonObject()Everything
Your own code on the other side of a boundary you own, such as a framework’s server-to-browser hand-offerror.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 APIerror.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();
}

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.

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");
}
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

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",
});
}

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.

// Server: the wire form, with the status of what is sent
const wire = error.toWireJsonObject();
return Response.json(wire, { status: wire.httpStatusCode });
// Client
const caught = castNiceError(await res.json());
if (err_auth.isExact(caught)) {
const hydrated = err_auth.hydrate(caught);
// hydrated.getContext(...) is now fully typed and real
}