@asleepace/try
Version:
TypeScript utilities for exception handling and errors-as-values.
76 lines (74 loc) • 1.53 kB
JavaScript
// src/index.ts
class Res extends Array {
static toError = (exception) => {
return exception instanceof Error ? exception : new Error(String(exception));
};
static from(tuple) {
return new Res(tuple);
}
static ok(value) {
return Res.from([value, undefined]);
}
static err(exception) {
return Res.from([undefined, Res.toError(exception)]);
}
constructor([value, error]) {
super(2);
this[0] = value;
this[1] = error;
}
get value() {
return this[0];
}
get error() {
return this[1];
}
get ok() {
return this.error === undefined;
}
isOk() {
return this.error === undefined;
}
isErr() {
return this.error !== undefined;
}
unwrap() {
if (this.isOk())
return this.value;
throw new Error(`Failed to unwrap result with error: ${this.error?.message}`);
}
unwrapOr(fallback) {
return this.value ?? fallback;
}
or = Try.catch;
toString() {
if (this.ok) {
return `Result.Ok(${String(this.value)})`;
} else {
return `Result.Error(${this.error?.message})`;
}
}
[Symbol.for("nodejs.util.inspect.custom")]() {
return this.toString();
}
}
class Try {
static catch(fn) {
try {
const output = fn();
if (output instanceof Promise) {
return output.then((value) => Res.ok(value)).catch((error) => Res.err(error));
} else {
return Res.ok(output);
}
} catch (e) {
return Res.err(e);
}
}
}
var vet = Try.catch;
export {
vet,
Try,
Res
};