@octabits-io/result
Expected errors are values, not exceptions.
import { ok, err, tryCatchAsync } from '@octabits-io/result';
import type { Result, OctError } from '@octabits-io/result';
function parsePort(raw: string): Result<number, OctError> {
const n = Number(raw);
return Number.isInteger(n) && n > 0 ? ok(n) : err({ key: 'invalid_port', message: `not a port: ${raw}` });
}
const port = parsePort(process.env.PORT ?? '');
if (!port.ok) return port; // propagate: the error is a value
listen(port.value); // narrowed: `value` exists only on `ok: true`
Result<T, E>—{ ok: true; value: T } | { ok: false; error: E }. A plain discriminated union: no class, no brand, no symbol, so two copies of this package are structurally identical and aResultfrom one library is aResultin another.OctError—{ key: string; message: string };keyis the discriminator in error unions and the wire key of an HTTP error response.OctErrorWithKey<K>narrows it.isOctError(a stringkeyand a stringmessage) /toOctErrorturn unknown thrown values into one.toOctError’s fallbacks: anOctErrorcomes back as is — anErrorinstance carrying akeyas a plain-object copy, so itsmessagesurvivesJSON.stringify; a string iskey: 'general'; any otherErroris itsnamesnake_cased (TypeError→type_error,Error→error), theErroritself not kept; anything else iskey: 'general',message: 'General error'.ok/err— construct with these, never with raw literals.tryCatch/tryCatchAsync— wrap throwing code (a vendor SDK,JSON.parse) into aResult(tryCatchAsyncalso catches a function that throws before it returns its promise, so it never rejects);isAbortErrorrecognises an aborted request.OctExceptionError— whattryCatchwraps a thrown value into (key: 'exception', with thecause) — one fixed key whatever was thrown, unliketoOctError, and the thrown value kept.
What is deliberately not here: the keyed HTTP error-response shapes
(ApiErrorResponse, ValidationApiError, …). Those are wire vocabulary — they
change when an API surface does — and live in @octabits-io/server.
Only unexpected errors — programming errors, invariant violations — are
thrown. Everything a caller could reasonably handle comes back as a value, and
propagates with if (!r.ok) return r.
When not to use it
- A programming error. A
Resultaround a bug hides it. An invariant that cannot hold, aswitchthat reached itsdefault, a dependency missing at boot — throw, and let the process say so. Only what a caller could reasonably handle is a value. - You want combinators. There is no
map,andThen,matchorOptionhere, and there will not be: the bare union is the design, so two copies of the package agree without a shared class. A pipeline-style error layer is neverthrow, Effect or fp-ts; aResultfrom here narrows into any of them with oneif. - You need the HTTP error shape.
OctErroris{ key, message }and nothing more. The wire responses — validation details, status mapping,ApiErrorResponse— are@octabits-io/server. - You already have
{ ok, value } | { ok, error }. Then you already interoperate: the type is structural, and nothing here is needed to consume aResultanother@octabits-iopackage returns. Install it forok/err,tryCatchand the sharedOctErrorvocabulary, not for compatibility. tryCatchas a resilience layer. It turns one throw into one value. Retries, timeouts and circuit breaking belong to the caller — or to a queue, where a failed attempt is meant to run again.
Frozen
This package is the vocabulary every @octabits-io package shares: the
workflow engine’s public view, the review layer’s apply side. It depends on nothing and it does not change: the runtime export list is
pinned by a test, and an addition is a new minor with a reason — never a
drive-by. Depend on it with a wide range (>=1 <2); there will be no reason to
pin.
License
MIT
From @octabits-io/result@1.0.3 in the platform repository.