Error handling without try
/catch
blocks.
yarn add errou
# If you're using NPM:
# npm install errou
Have you ever written some code like:
import fs from 'fs';
let contents;
try {
contents = readFileSync('foo.txt', 'utf8');
} catch (error) {
// Deal with `error` here.
}
console.log(`Contents: ${contents}`);
With errou
, no more. It abstracts those ugly use cases of try
/catch
blocks for you. It supports both synchronous and asynchronous functions – in this last case, the function must return a Promise, which will be resolved by errou
.
import fs from 'fs';
import errou from 'errou';
const call = errou(() => fs.readFileSync('foo.txt', 'utf8'));
if (call.ok) {
console.log(`Contents: ${call.data}`);
}
if (!call.ok) {
// Deal with `call.error` here.
}
In the previous example, we passed an arrow function, which will be invoked by errou
. You can also pass a function reference:
function someFunction(a: string, b: number) {
if (b % 2 !== 0) {
throw new Error('Only even numbers are allowed.');
}
return { a, b };
}
const call = errou(someFunction, 'Foo', 10);
// call.ok
// call.data
// call.error
TypeScript will complain if errou
last arguments does not match with the first function's argument types.
If the function has some overloads, you must pass a lambda as done in the fs.readFile
example.
By default, call.error
has the unknown
type. You may assert that type to your desired Error
instance.
Asserting the error
type
const call = errou(someFn, ...args);
if (!call.ok) {
console.log((call.error as Error).message);
}
lffg and contributors.
MIT License, see the included MIT file.