@cceevv/tryit
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

tryit [no try catch]

Simple wrapper for synchronous or asynchronous error handling, to hell with try catch.

npm GitHub Workflow Status Coverage Status npm bundle size npm type definitions GitHub

English · 简体中文


Install

pnpm add @cceevv/tryit
# or
yarn add @cceevv/tryit
# or
npm i @cceevv/tryit

Usage

import tryit from "@cceevv/tryit";

function syncDemo() {
  const DefaultValue = {a: 0, b: ''}
  const [data = DefaultValue, err] = tryit(() => {
    return JSON.parse('--------{"a":1234, "b":"bbb"}')
  })
  if (err) {
    console.log('xxxxxxxxxx', err)
    return;
  }
  console.log('handle data...', data)
}

async function asyncDemo() {
  const promise = new Promise((resolve, reject) => {
    resolve('resolve data');
    // reject('reject error');
  })

  const [data, err] = await tryit(promise);
  if (err) {
    console.log('xxxxxxxxxx', err)
    return;
  }
  console.log('handle data...', data)
}

async function followedReturnedPromise() {
  const [data, err] = await tryit(async () => {
    return Promise.resolve(666)
  });
  if (err) {
    console.log('xxxxxxxxxx', err)
    return;
  }
  console.log('handle data...', data)
}

API

export declare function tryit<T, U = Error>(func: (() => T)): [T, U];
export declare function tryit<T, U = Error>(func: (() => Promise<T>)): Promise<[T, U]>;
export declare function tryit<T, U = Error>(promise: Promise<T>): Promise<[T, U]>;

License

MIT License (c) cceevv

Package Sidebar

Install

npm i @cceevv/tryit

Weekly Downloads

1

Version

1.0.2

License

MIT

Unpacked Size

13.1 kB

Total Files

9

Last publish

Collaborators

  • cceevv