try/catch wrapper for easy error handling in js
npm install try-to-jsA lightweight try/catch wrapper for easy error handling that improves code readability by removing the clutter of traditional try/catch blocks.
To install the package, run:
``bash`
npm i try-to-js
`javascript
import { tryTo } from "try-to-js";
function withoutUsingTryTo() {
let res: ReturnType
try {
res = syncFunctionThatCanThrowError();
} catch (err) {
console.log(err);
return;
}
// do something with res
}
`
`javascript
import { tryTo } from "try-to-js";
function usingTryTo() {
const [err, res] = tryTo(syncFunctionThatCanThrowError);
if (err) {
console.log(err);
return;
}
// do something with res
}
`
- If no error is thrown, the err value will be undefined, and res will hold the returned value of syncFunctionThatCanThrowError().err
- If an error is thrown, the value will contain the error that was thrown, and res will be undefined`.