An open-source, self-hosted system for apps built with web technologies.
A refusal the System writes always tells the Program why; failures beneath it stay hidden outside debugging
zohayrslilehc7531bc706dc
diff --git a/source/libs/request-outcome.ts b/source/libs/request-outcome.tsindex c8aa950..801aecb 100644--- a/source/libs/request-outcome.ts+++ b/source/libs/request-outcome.ts@@ -8,16 +8,28 @@ export function succeeded<Result>(result: Result): RequestOutcome<Result> {return { success: true, result }}+/**+ * A failure as the one who asked may read it. A refusal the System wrote itself, a plain `Error`,+ * always says why, since a Program needs the reason to correct what it asked. Anything else, such as+ * a failure in the runtime, an operating system error carrying its `code`, or a library's own error,+ * is told only while `disclose` allows it, so what lies beneath does not reach a Program.+ */export function failed(exception: unknown, disclose = true): RequestOutcome<never> {return {success: false,- error: disclose && exception instanceof Error ? exception.message : "An unknown exception occurred"+ error: exception instanceof Error && (disclose || refusal(exception)) ? exception.message : "An unknown exception occurred"}}+/** Whether an error is the System refusing in its own words, rather than something failing beneath it. */+function refusal(exception: Error) {++ return Object.getPrototypeOf(exception) === Error.prototype && !("code" in exception)+}+export function unwrap<Result>(outcome: RequestOutcome<Result>): Result {if (!outcome || typeof outcome !== "object" || !("success" in outcome)) throw new Error("The boundary returned an invalid outcome")diff --git a/tests/request-outcome.test.ts b/tests/request-outcome.test.tsnew file mode 100644index 0000000..3a5d96f--- /dev/null+++ b/tests/request-outcome.test.ts@@ -0,0 +1,15 @@+import { expect, test } from "vitest"+import { failed } from "@libs/request-outcome"++test("a refusal the System wrote reaches the one who asked, even when nothing else may", () => {+ expect(failed(new Error(`The process "settings" already exists with a different launch`), false))+ .toEqual({ success: false, error: "The process \"settings\" already exists with a different launch" })+})++test("what fails beneath the System stays hidden unless disclosure is allowed", () => {+ const system = Object.assign(new Error("ENOENT: no such file or directory, open '/home/owner/.secret'"), { code: "ENOENT" })+ for (const exception of [new TypeError("Cannot read properties of undefined"), system, "a thrown string"]) {+ expect(failed(exception, false)).toEqual({ success: false, error: "An unknown exception occurred" })+ }+ expect(failed(new TypeError("Cannot read properties of undefined"), true)).toEqual({ success: false, error: "Cannot read properties of undefined" })+})