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);
- Avoids re-assignments (no need for
let
) - Automatic Typescript typing
- Supports
try
,catch
, andfinally
blocks - Supports
async
functions - No dependencies
npm install try-function
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.");
}
);
For a list of changes and releases, see the changelog.
Found a bug, have a question or looking to improve try-function? Open an issue, start a discussion or submit a PR!