@el3um4s/to-try
v1.0.1
Published
Wrapper for error handling without try-catch
Downloads
90
Maintainers
Readme
To Try
Wrapper for error handling without try-catch
Based on:
- Functional Try-catch In JavaScript
- How to avoid try/catch statements nesting/chaining in JavaScript?
- Let’s Clean Up: Ugly Try-Catches in JavaScript!
- scopsy/await-to-js
- Coly010/no-try
Install and use the package
To use the package in a project:
npm i @el3um4s/to-try
and then in a file:
import { toTry, toTryAsync } from "@el3um4s/to-try";
// Without a custom error handler
const [result, error] = toTry(() => myThrowableMethod());
// With a custom error handler
const [res, err] = toTry(
() => myThrowableMethod(),
error => {
console.log(error);
}
);
// Handle methods that return a Promise without a custom error handler
const [res2, err2] = await toTryAsync(() => myAsyncThrowableMethod());
// Handle methods that return a Promise with a custom error handler
const [res3, err3] = await toTryAsync(
() => myAsyncThrowableMethod(),
error => {
console.log(error);
}
);
// Use result
if (error || err || err2 || err3) {
// Show error alert
}
sendMyResultToMethod(result);