@almank/try-catch

Try/Catch made simple.

Usage no npm install needed!

<script type="module">
  import almankTryCatch from 'https://cdn.skypack.dev/@almank/try-catch';
</script>

README

@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