try-to-js
v1.0.4
Published
try/catch wrapper for easy error handling in js
Readme
try-to-js
A lightweight try/catch wrapper for easy error handling that improves code readability by removing the clutter of traditional try/catch blocks.
Badges
Installation
To install the package, run:
npm i try-to-jsExamples
Without using try-to-js
import { tryTo } from "try-to-js";
function withoutUsingTryTo() {
let res: ReturnType<typeof syncFunctionThatCanThrowError> | undefined;
try {
res = syncFunctionThatCanThrowError();
} catch (err) {
console.log(err);
return;
}
// do something with res
}Using try-to-js
import { tryTo } from "try-to-js";
function usingTryTo() {
const [err, res] = tryTo(syncFunctionThatCanThrowError);
if (err) {
console.log(err);
return;
}
// do something with res
}Notes
- If no error is thrown, the
errvalue will beundefined, andreswill hold the returned value ofsyncFunctionThatCanThrowError(). - If an error is thrown, the
errvalue will contain the error that was thrown, andreswill beundefined.
