@fajarnugraha37/error
Version:
Runtime-agnostic error handling library with structured errors, adapters, and validation support for Bun, Node.js, and browsers
57 lines (54 loc) • 2.18 kB
TypeScript
import { AppError } from './app-error.js';
type Result<T, E = AppError> = {
ok: true;
value: T;
error: null;
} | {
ok: false;
value: null;
error: E;
};
declare function ok<T>(value: T): ResultWrapper<T, never>;
declare function err<E = AppError>(error: E): ResultWrapper<never, E>;
declare class ResultWrapper<T, E = AppError> {
private readonly result;
constructor(result: Result<T, E>);
unwrapResult(): Result<T, E>;
isOk(): boolean;
isErr(): boolean;
map<U>(fn: (value: T) => U): ResultWrapper<U, E>;
mapAsync<U>(fn: (value: T) => Promise<U>): Promise<ResultWrapper<U, E>>;
mapErr<F>(fn: (error: E) => F): ResultWrapper<T, F>;
flatMap<U, F>(fn: (value: T) => ResultWrapper<U, F>): ResultWrapper<U, E | F>;
tap(fn: (value: T) => void): ResultWrapper<T, E>;
tapErr(fn: (error: E) => void): ResultWrapper<T, E>;
unwrap(): T;
unwrapErr(): E;
unwrapOr(defaultValue: T): T;
unwrapOrElse(fn: (error: E) => T): T;
match<U>(handlers: {
ok: (value: T) => U;
err: (error: E) => U;
}): U;
toPromise(): Promise<T>;
and<U, F>(other: ResultWrapper<U, F>): ResultWrapper<[T, U], E | F>;
or<F>(other: ResultWrapper<T, F>): ResultWrapper<T, E | F>;
}
declare function safeAwait<T>(promise: PromiseLike<T>): Promise<ResultWrapper<T, AppError>>;
declare function safeFunc<T, A extends any[]>(fn: (...args: A) => T, ...args: A): ResultWrapper<T, AppError>;
declare function isOk<T, E>(result: Result<T, E>): result is {
ok: true;
value: T;
error: null;
};
declare function isErr<T, E>(result: Result<T, E>): result is {
ok: false;
value: null;
error: E;
};
declare function unwrap<T, E>(result: Result<T, E>): T;
declare function unwrapErr<T, E>(result: Result<T, E>): E;
declare function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T;
declare function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>;
declare function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>;
export { type Result, ResultWrapper, err, isErr, isOk, map, mapErr, ok, safeAwait, safeFunc, unwrap, unwrapErr, unwrapOr };