dotry
TypeScript icon, indicating that this package has built-in type declarations

1.4.1 • Public • Published

dotry

Catch errors without try...catch...

Tired of writing too much try {} catch {}, try this funny tool, it wraps the error and the return value into a two-item array, which we can extract like this const [err, res] = _try(...).

And this function supports all JavaScript functions, such as Function, AsyncFunction, GeneratorFunction and AsyncGeneratorFunction, and Promise instances, regardless of transpiling to es5, es2015, es2016 or other versions.

Warning: the main function of this package has been merged into @ayonli/jsext, this package will stay for a while, and will be deprecated in the near future.

Install

npm i dotry

Example

Regular Function

import _try from "dotry";

function check(str: string) {
    if (somethingWentWrong()) {
        throw new Error("something went wrong");
    }

    return str;
}

let [err, res] = _try(check, "Hello, World!");

// Or simply
let [err, res] = _try(() => {
    if (somethingWentWrong()) {
        throw new Error("something went wrong");
    }

    return "Hello, World!";
});

Async Function

import _try from "dotry";

async function checkAsync(str: string) {
    if (await somethingWentWrong()) {
        throw new Error("something went wrong");
    }

    return await Promise.resolve(str);
}

let [err, res] = await _try(checkAsync, "Hello, World!");

// Or
let [err, res] = await _try(checkAsync("Hello, World!"));

// Or simply
let [err, res] = await _try(async () => {
    if (await somethingWentWrong()) {
        throw new Error("something went wrong");
    }

    return "Hello, World!";
});

Generator Function

import _try from "dotry";

function* iterate(...data: number[]) {
    for (let num of data) {
        if (num > 9) {
            throw new RangeError(`number ${num} is out of range`);
        } else {
            yield num;
        }
    }
}

for (let [err, value] of _try(iterate, 1, 2, 3, 4)) {
    // ...
}

// Or
for (let [err, value] of _try(iterate(1, 2, 3, 4))) {
    // ...
}

Async Generator Function

import _try from "dotry";

async function* iterateAsync(...data: number[]) {
    for (let num of data) {
        if (num > 9) {
            throw new RangeError(`number ${num} is out of range`);
        } else {
            yield num;
        }
    }
}

for await (let [err, value] of _try(iterateAsync, 1, 2, 3, 4)) {
    // ...
}

// Or
for await (let [err, value] of _try(iterateAsync(1, 2, 3, 4))) {
    // ...
}

Happy Coding!

Package Sidebar

Install

npm i dotry

Weekly Downloads

0

Version

1.4.1

License

MIT

Unpacked Size

16.7 kB

Total Files

6

Last publish

Collaborators

  • ayonli