Skip to content
This repository has been archived by the owner on Jul 12, 2020. It is now read-only.

Latest commit

 

History

History
96 lines (65 loc) · 2.47 KB

README.md

File metadata and controls

96 lines (65 loc) · 2.47 KB

errou

Error handling without try/catch blocks.

Actions Status NPM Uses TypeScript

Installing

yarn add errou

# If you're using NPM:
# npm install errou

Why?

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.

Usage

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.

The error type

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);
}

Authors and License

lffg and contributors.

MIT License, see the included MIT file.