Skip to content

A tiny utility for using `const` with `try/catch` blocks and get automatic typing.

License

Notifications You must be signed in to change notification settings

alexnault/try-function

Repository files navigation

try-function

NPM version Test coverage Size

A tiny utility for using const with try/catch blocks and get automatic typing.

In other word, try-function converts this:

let integer: number | undefined;
try {
  integer = parseInt("7");
} catch (error) {
  console.log(error);
}

... to this:

import { tryFn } from "try-function";

const integer = tryFn(() => parseInt("7"), console.log);

Highlights

  • Avoids re-assignments (no need for let)
  • Automatic Typescript typing
  • Supports try, catch, and finally blocks
  • Supports async functions
  • No dependencies

Installation

npm install try-function

Example

Here's an advanced example showcasing all features (try/catch/finally in a async format):

import { tryFn } from "try-function";

const text = await tryFn(
  async () => {
    const text = await readFile("file.txt");
    return text;
  },
  async (error) => {
    await log("An error occured: ", error);
    return "Error";
  },
  async () => {
    await log("Operation completed.");
  }
);

Changelog

For a list of changes and releases, see the changelog.

Contributing

Found a bug, have a question or looking to improve try-function? Open an issue, start a discussion or submit a PR!

About

A tiny utility for using `const` with `try/catch` blocks and get automatic typing.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published