UNPKG

@dschz/try-catch

Version:

Simple try-catch utility function for JavaScript

48 lines (46 loc) 1.78 kB
type Success<T> = [error: null, data: T]; type Failure<E extends Error = Error> = [error: E, data: null]; type Result<T, E extends Error = Error> = Success<T> | Failure<E>; /** * Wraps a promise and returns a tuple `[error, data]`. * * @template T - The resolved type of the promise * @template E - The error type, defaults to `Error` * @param input - A promise to wrap * @returns A promise resolving to `[null, data]` on success or `[error, null]` on failure * * @example * ```ts * const [err, data] = await tryCatch(fetch("/api/data")); * ``` */ declare function tryCatch<T, E extends Error = Error>(input: Promise<T>): Promise<Result<T, E>>; /** * Wraps a synchronous function and returns a tuple `[error, data]`. * * @template T - The return type of the function * @template E - The error type, defaults to `Error` * @param input - A synchronous function that may throw * @returns `[null, data]` on success or `[error, null]` on failure * * @example * ```ts * const [err, data] = tryCatch(() => JSON.parse('{"a":1}')); * ``` */ declare function tryCatch<T, E extends Error = Error>(input: () => Exclude<T, Promise<unknown>>): Result<T, E>; /** * Wraps an async function and returns a tuple `[error, data]`. * * @template T - The resolved type of the returned promise * @template E - The error type, defaults to `Error` * @param input - An async function or a function returning a promise * @returns A promise resolving to `[null, data]` on success or `[error, null]` on failure * * @example * ```ts * const [err, data] = await tryCatch(async () => fetchData()); * ``` */ declare function tryCatch<T, E extends Error = Error>(input: () => Promise<T>): Promise<Result<T, E>>; export { type Failure, type Result, type Success, tryCatch };