1.0.2 • Published 1 year ago

@cceevv/tryit v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

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