Catch errors without try...catch...
npm install dotryCatch 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 thisconst [err, res] = _try(...).
And this function supports all JavaScript
functions, such as Function, AsyncFunction, GeneratorFunction andAsyncGeneratorFunction, and Promise instances, regardless of transpiling toes5, 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.
``sh`
npm i dotry
`ts
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!";
});
`
`ts
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!";
});
`
`ts
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))) {
// ...
}
`
`ts
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!