try-handler
TypeScript icon, indicating that this package has built-in type declarations

0.0.5 • Public • Published

Try Handler

Try handler is a powerful utility that wraps try-catch blocks in a function, allowing you to handle errors in a more elegant way, without the need to write try-catch blocks in your code.

Installation

To install the utilities, you can use the following command:

npm install  try-handler
pnpm add  try-handler
yarn add try-handler
bun add try-handler

Usage

The try-handler package provides two functions, tryAsync and trySync, which allow you to handle errors in asynchronous and synchronous functions, respectively. The functions return an array with two elements, the first element is the error object, and the second element is the data returned by the function. These functions are useful when you want to handle errors in a more elegant way, without the need to write try-catch blocks in your code.

Types

type TryResult<T> = [ErrorHandling, T | undefined];
type Callback<T> = () => T;

interface ErrorHandling {
  message: string;
  instance: {
    stack: string | undefined;
    name: string;
    cause: unknown;
  };
}

Examples

import { tryAsync, trySync } from 'try-handler';

const asyncGoodFunction = async () => Promise.resolve('Hello World');
const asyncBadFunction = async () =>
  Promise.reject(new Error('An error occurred'));

const syncGoodFunction = () => 'Hello World';
const syncBadFunction = () => {
  throw new Error('An error occurred');
};

const [error, data] = await tryAsync(asyncGoodFunction);
console.log(data); // Hello World
console.log(error); // null

const [error, data] = await tryAsync(asyncBadFunction);
console.log(data); // null
console.log(error.message); // Error: An error occurred

const [error, data] = trySync(syncGoodFunction);
console.log(data); // Hello World
console.log(error); // null

const [error, data] = trySync(syncBadFunction);
console.log(data); // null
console.log(error.message); // An error occurred

🛠️ Tools

Typescript ESLint Prettier NodeJS

Authors

ImRLopezAG

🔗 Links

portfolio linkedin twitter

Package Sidebar

Install

npm i try-handler

Weekly Downloads

2

Version

0.0.5

License

GPL-3.0-only

Unpacked Size

6.86 kB

Total Files

6

Last publish

Collaborators

  • imrlopez.ag