errou
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

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 = readFile("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.

Usage

import fs from "fs";
import errou from "errou";
 
const call = errou(() => fs.readFile("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 or pass the correct Error type to the second generic that errou accepts.

Asserting the error type
const call = errou(someFn, ...args);
 
if (!call.ok) {
  console.log((call.error as Error).message);
}
Passing the correct error type as the second errou generic
const call = errou<typeof someFn, Error>(someFn, ...args);
 
if (!call.ok) {
  console.log(call.error.message);
}

Note that you should pass the type of the function as the first generic.

Authors and License

lffg and contributors.

MIT License, see the included MIT file.

Readme

Keywords

none

Package Sidebar

Install

npm i errou

Weekly Downloads

0

Version

2.0.0

License

MIT

Unpacked Size

8.02 kB

Total Files

8

Last publish

Collaborators

  • lffg