Typesafe error handling (inspired by Go) & data absence protection for TypeScript apps (NodeJS/Browser).
🚧 Should work, but all of this is still a bit "work-in-progress"!
npm i @aripalo/result
Some irrelevant code for demonstration purposes:
async function randomErrorHelloWorld(): Promise<string> {
if (Math.random() < 0.5) {
throw new Error("Random error occurred");
}
return "Hello World!";
}
import { Result } from "@aripalo/result";
const [value, err] = await Result(randomErrorHelloWorld());
if (err) {
assert(value === null); // true
assert(err instanceof Error); // true
} else {
assert(typeof value === "string"); // true
assert(err === null); // true
}
“There are many like it, but this one is mine.”
Writing asynchronous code with async
/await
looks simple, but once procedural code that depends on the output of previous async steps is being introduced with bit more complex error handling requirements, things start to become complex from control flow perspective.
There are many great alternative solutions to this problem; This one just happens to be the pattern I personally prefer to use.
-
Go-inspired, error as return value
-
Returned error is always an instance of
Error
-
Return value (type
Maybe
) is a Tuple with either value or error present and the other always set tonull
:type Maybe<T> = [value: T, err: null] | [value: null, err: Error];
-
Data absence protection: By default, values that resolve to
undefined
ornull
will internally thrown an error, resulting into:[value: null, err: Error]
-
Primarily aimed for
async
functions and Promise objects, but works with synchronous functions too: Anything that is throwable, i.e. "can throw/reject". -
Works both in NodeJS and Browser environments
const [value, err] = await Result(randomErrorHelloWorld());
if (err) {
// handle err, for example return early
return;
}
// do something with the value
If you're only interested in "did the operation succeed", without caring about the return value:
const [, err] = await Result(randomErrorHelloWorld());
if (err) {
// handle err
}
When you don't really care if the operation fails, but if it succeeded do something with the return value:
const [value] = await Result(randomErrorHelloWorld());
if (value) {
// do something with value
}
If your throwable returns/resolves without meaningful data on success, you may specify meaningful: false
to prevent the data absence protection:
const [value, err] = await Result(Promise.resolve(undefined), {
meaningful: false,
});
if (err) {
// handle err
} else {
assert(typeof value === "undefined"); // true
}