@borisnl/tried
v1.0.6
Published
A simple, small, zero dependency try-catch wrapper.
Downloads
53
Readme
tried
A simple, small, zero dependency try-catch wrapper. It provides a safe way to handle code that may throw errors, both synchronously and asynchronously. It allows for fallback values when an error occurs.
Installation
Install the package using npm install @borisnl/tried or your package manager's equivalent.
npm install @borisnl/triedSyntax
Try<T>(
fn: () => T | Promise<T>,
fallback?: T | (() => T | Promise<T>)
): T | Promise<T>fn: The primary function to execute.fallback: (Optional) The fallback value or function iffnthrows an error.
Return Value
- Returns the result of
fnif it executes without errors. - Returns
fallbackiffnthrows an error. - Returns
nulliffnfails and nofallbackis provided.
Examples
Synchronous Usage
Try(() => 2 + 2); // Returns 4
Try(() => {
throw new Error();
}, "fallback"); // Returns "fallback"Asynchronous Usage
await Try(async () => 2 + 2); // Returns 4
await Try(async () => {
throw new Error();
}, "fallback"); // Returns "fallback"Fallback as a Function
Try(
() => {
throw new Error();
},
() => "fallback"
); // Returns "fallback"
await Try(
async () => {
throw new Error();
},
async () => "fallback"
); // Returns "fallback"