Recipes
How-to guides for tasks that come up when you handle issues. For every export, see the API reference; for why issues behave as they do, see the concepts.
How to try several recoveries in order
Use firstOf with the recoveries in the order to try them. It stops at the first success; when all fail, it fails with the last one's error. The list can't be empty. Its residue is the widest of the list's, with no union, so a fail needs no annotation.
import { issue } from "@sekhmet/issue/issue";
import { fail, firstOf, succeed } from "@sekhmet/issue/recovery";
import { assertEquals } from "@std/assert";
const notFound = issue<string, number>({
value: "app.json",
code: "config/NotFound",
message: "No config file.",
});
/** The port the only succeeding recovery yields. */
const PORT = 8080;
const recovery = firstOf([fail("no backup"), fail("no remote"), succeed(PORT)]);
assertEquals(
(await notFound.attempt(recovery).wait()).unwrap(),
PORT,
"the first success should handle the issue",
);How to retry a flaky recovery
Use retry with how many more times to run it after a failure. Each run starts once the previous one has settled; when they all fail, the last error is kept.
import { Err, Ok } from "@sekhmet/enum/result";
import { issue } from "@sekhmet/issue/issue";
import { sync } from "@sekhmet/issue/recovery";
import { assertEquals } from "@std/assert";
const notFound = issue<string, number>({
value: "app.json",
code: "config/NotFound",
message: "No config file.",
});
/** The try that first succeeds. */
const SUCCEEDS_ON = 3;
let tries = 0;
const flaky = sync((_path: string) => {
tries += 1;
return tries < SUCCEEDS_ON ? Err(`try ${tries} failed`) : Ok(9000);
});
const ended = await notFound.attempt(flaky.retry({ times: 4 })).wait();
assertEquals(ended.isHandled(), true, "a retry should handle the issue");
assertEquals(tries, SUCCEEDS_ON, "retry should stop at the first success");How to recover only some values
Use when with a test on the value, and the error to fail with for a value that doesn't pass. The recovery doesn't run for those.
import { issue } from "@sekhmet/issue/issue";
import { type Recovery, succeed } from "@sekhmet/issue/recovery";
import { assertEquals } from "@std/assert";
/** The error a value that isn't a dev config fails with. */
const NOT_DEV = "only dev configs have a default";
const useDevPort: Recovery<string, number, never> = succeed(3000);
const devOnly = useDevPort.when({
test: (path) => path.startsWith("dev"),
otherwise: NOT_DEV,
});
const app = issue<string, number>({
value: "app.json",
code: "config/NotFound",
message: "No config file.",
});
const ended = await app.attempt(devOnly).wait();
assertEquals(
ended.unwrapFailed(),
NOT_DEV,
"a value that isn't a dev config should fail with otherwise",
);
assertEquals(app.isUnhandled(), true, "the issue should stay unhandled");How to recover a wrapped issue through its cause
A wrapped issue's value is { cause }. Recover the cause, then hand its residue up: attempt the cause inside a recovery of the wrapper, and turn how that attempt ended into the wrapper's outcome with toOutcome. The cause is held as a mini Issue, so view it as a main one with Issue.fromMini (the view shares its state) to chain. mapInput adapts a recovery of the cause's value to the wrapper's.
import { Issue, issue, type Wrapped } from "@sekhmet/issue/issue";
import { Recovery, succeed } from "@sekhmet/issue/recovery";
import { assertEquals } from "@std/assert";
const notFound = issue<string, number>({
value: "app.json",
code: "config/NotFound",
message: "No config file.",
});
const loadFailed = notFound.wrap({
code: "config/LoadFailed",
message: "Couldn't load the config.",
});
/** The port the cause is recovered with. */
const PORT = 8080;
const viaCause = new Recovery(({ cause }: Wrapped<string, number>) => {
return Issue.fromMini(cause)
.attempt(succeed(PORT))
.map((ended) => ended.toOutcome());
// {}
});
await loadFailed.attempt(viaCause).wait();
assertEquals(
loadFailed.unwrapResidue(),
PORT,
"the wrapper should take its cause's residue",
);
assertEquals(
notFound.unwrapResidue(),
PORT,
"the cause itself should be handled",
);How to recover the issue in an Err
A function that can fail with an issue returns Result<R, Issue<T, R>>. Use recoverWith to attempt the issue. It settles as an Outcome: the Err becomes Ok(residue) once the issue is handled, stays an Err with the same issue if the recovery fails, and is Panicked if the recovery panicked.
import { Err, Ok, type Result } from "@sekhmet/enum/result";
import { type Issue, issue, recoverWith } from "@sekhmet/issue/issue";
import { succeed } from "@sekhmet/issue/recovery";
import { assertEquals } from "@std/assert";
function readPort(path: string): Result<number, Issue<string, number>> {
if (path === "app.json") return Ok(80);
return Err(
issue({ value: path, code: "config/NotFound", message: "No config file." }),
);
}
/** The port the issue is recovered with. */
const DEV_PORT = 3000;
const port = await recoverWith({
result: readPort("dev.json"),
recovery: succeed(DEV_PORT),
}).wait();
assertEquals(
port.unwrap(),
DEV_PORT,
"the recovered Err should become Ok with the residue",
);How to handle an issue without a recovery
When the residue is already at hand, use handle. It switches an unhandled issue at once, and leaves a handled one as it is.
import { issue } from "@sekhmet/issue/issue";
import { assertEquals } from "@std/assert";
const notFound = issue<string, number>({
value: "app.json",
code: "config/NotFound",
message: "No config file.",
});
/** The residue the issue is handled with first. */
const PORT = 8080;
assertEquals(
notFound.handle(PORT).isHandled(),
true,
"the first handle should switch the issue",
);
assertEquals(
notFound.handle(3000).isAlreadyHandled(),
true,
"a second handle should find the issue already handled",
);
assertEquals(
notFound.unwrapResidue(),
PORT,
"the issue should keep its first residue",
);How to narrow an issue's state
Read the state with state() and narrow that, not the issue: the issue switches in place, but a state is a snapshot that never changes, so its isUnhandled and isHandled are type guards, and so are isUnhandledAnd and isHandledAnd, which also test the value or residue. Narrowed, the variant's value reads directly with enum's union.
import { union } from "@sekhmet/enum/core/mini";
import { issue } from "@sekhmet/issue/issue";
import { assertEquals } from "@std/assert";
const notFound = issue<{ readonly path: string }, number>({
value: { path: "app.json" },
code: "config/NotFound",
message: "No config file.",
});
const current = notFound.state();
if (current.isUnhandled()) {
const { path } = union(current);
assertEquals(path, "app.json", "the narrowed state should read its path");
}How to render an issue for a person
Use render. It prints the code and message, the hint and docs when there are any, and each cause of a wrapped chain; a handled issue is marked.
import { issue } from "@sekhmet/issue/issue";
import { assertEquals } from "@std/assert";
const notFound = issue<string, number>({
value: "app.json",
code: "config/NotFound",
message: "No config file at `app.json`.",
hint: "Create one.",
docs: "https://example.com/config",
});
assertEquals(
notFound.render(),
[
"config/NotFound: No config file at `app.json`.",
" hint: Create one.",
" docs: https://example.com/config",
].join("\n"),
"render should print the heading, then the hint and docs",
);