defaulterfun v1.0.0
defaulterfun
: Gracefully handle functions throwing errors - NPM Package
Overview
defaulterfun
is a lightweight npm package designed to safely execute functions that might throw errors. Instead of crashing the application, it gracefully handles errors and returns a specified default value.
Installation
You can install the package via npm:
npm install handle-errors
or using yarn:
yarn add handle-errors
Usage
Import the package and use it to wrap functions that may throw errors:
import { safeExecute } from "handle-errors";
const riskyFunction = () => {
if (Math.random() > 0.5) {
throw new Error("Random error occurred");
}
return "Success!";
};
const result = safeExecute(riskyFunction, "Default Value");
console.log(result); // Either "Success!" or "Default Value"
With Async Functions
The package also supports async functions:
const asyncRiskyFunction = async () => {
if (Math.random() > 0.5) {
throw new Error("Random async error");
}
return "Async Success!";
};
(async () => {
const result = await safeExecuteAsync(asyncRiskyFunction, "Default Async Value");
console.log(result); // Either "Async Success!" or "Default Async Value"
})();
API
safeExecute<T>(fn: () => T, defaultValue: T): T
Executes the given function and returns its result. If an error is thrown, it returns the provided default value.
Parameters
fn: () => T
- The function to execute.defaultValue: T
- The value to return in case of an error.
Returns
- The result of
fn()
if successful, otherwisedefaultValue
.
safeExecuteAsync<T>(fn: () => Promise<T>, defaultValue: T): Promise<T>
Executes an async function and returns its result. If an error occurs, it resolves with the default value.
Parameters
fn: () => Promise<T>
- The async function to execute.defaultValue: T
- The value to return in case of an error.
Returns
- A Promise resolving to either the result of
fn()
ordefaultValue
.
Use Cases
- Handling API calls without breaking the app.
- Preventing crashes due to unexpected function failures.
- Providing fallback values for unreliable functions.
- Ensuring stability in production applications.
License
This package is licensed under the MIT License.
Contributing
Contributions are welcome! Feel free to submit a pull request or open an issue.
Author
Created by Saqlain Ansari.
5 months ago