@almank/try-catch
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

@almank/try-catch

Try/Catch made simple

InstallOverviewUsageDevelopment

@almank/try-catch provides helpers to try catch your functions and promises.

Install

Using npm

npm install @almank/try-catch

Using yarn

yarn add @almank/try-catch

Overview

import { tryCatch, tryCatchPromise } from "@almank/try-catch";

const [result, error] = tryCatch(method, ...args);

const [result, error] = await tryCatchPromise(method, ...args);

Usage

tryCatch

import { tryCatch } from "@almank/try-catch";

const someFunction = name => {
  if (name === "Christoffer") {
    throw new Error("Oh no!");
  }

  return name;
};

const [result, error] = tryCatch(someFunction, "Christoffer");

console.log(result); // null
console.log(error); // "Error: Oh no!"

const [result, error] = tryCatch(someFunction, "Mathias");

console.log(result); // "Mathias"
console.log(error); // null

tryCatchPromise

import { tryCatchPromise } from "@almank/try-catch";

const getResult = fail =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
        if (fail) {
            reject(Error("Failed"));
        }
      resolve("results arrived");
    }, 1000);
  });


const someFunction = async () => {
  const [result, error] = await tryCatchPromise(getResult);

  console.log(result); // "results arrived"
  console.log(error); // null

  const [result, error] = await tryCatchPromise(getResult, true);

  console.log(result); // null
  console.log(error); // Error: Failed
};

Development

Installing dependencies

npm i

Running tests

npm test

Package Sidebar

Install

npm i @almank/try-catch

Weekly Downloads

2

Version

1.0.1

License

MIT

Unpacked Size

4.87 kB

Total Files

5

Last publish

Collaborators

  • almank