errgo-ts
Version:
A lightweight error handling library inspired by Go and Rust.
58 lines (57 loc) • 1.87 kB
TypeScript
import type { NotPromise, Result } from "./types.js";
/**
* Executes the provided function, returning a `Result` object containing either the functions's
* return value if successful, or its thrown error if it fails.
*
* Provides overloads for both synchronous and asynchronous actions.
*
* *This function will ***never*** throw.*
*
* @param action - the function to execute that may throw an error
* @returns `{ err: Error }` if `action` throws, else `{ val: T }`
* @example
* // Synchronous usage
* const res = tryCatch(() => fs.readFileSync(myFile, "utf-8"));
*
* // Async usage
* const res = await tryCatch(() => fetch("/data"));
*
* @example
* // Using tryCatch for granular error handling
* const resp = await tryCatch(() => fetch("/api/data"));
* if (resp.err) {
* throw new Error("Failed to fetch data", { cause: resp.err });
* }
* const json = await tryCatch(() => resp.val.json());
* if (json.err) {
* throw new Error("Failed to parse response body", { cause: json.err });
* }
* const result = tryCatch(() => processData(json.val));
* if (result.err) {
* throw new Error("Failed to process data", { cause: result.err });
* }
* return result.val;
*
* // Equivalent granular error handling with try/catch blocks
* let resp;
* try {
* resp = await fetch("/api/data")
* } catch (e) {
* throw new Error("Failed to fetch data", { cause: e });
* }
* let json;
* try {
* json = await resp.json();
* } catch (e) {
* throw new Error("Failed to parse response body", { cause: e });
* }
* let result;
* try {
* result = processData(json);
* } catch (e) {
* throw new Error("Failed to process data", { cause: e });
* }
* return result;
*/
export declare function tryCatch<T>(action: () => NotPromise<T>): Result<T>;
export declare function tryCatch<T>(action: () => Promise<T>): Promise<Result<T>>;