errors-in

1.2.1 • Public • Published

errorsIn

Removing try-catch boilerplate in a natural style with error handlers.

Quick Start

Installation

npm install errors-in

Common Usage

const errorsIn = require("errors-in");

const run = errorsIn(() => {
    throw new Error("Whoops!");
})
.willBeCaughtBy(err => {
    console.log("Bob caught the error first.");
    throw err;
}, anotherCatcher)
.and(async err => {
    console.log("Alice caught the error async.");
});

Other usages and sorry

Return Value

A value can be returned both at the function and the catcher. A Joi style validation result can be mocked in this way.

const run = errorsIn(number => {
    if (number > 0.5) {
        return { number };
    } else {
        const err = new Error("Nah");
        throw err;
    }
})
.willBeCaughtBy((err, number) => {
    return { number, error: err };
});

Catcher Arguments

The first argument of the catcher will obviously be the error. The rest are the arguments received in the function forwarded.

const catcher = (err, req, res) => {
    console.log(err);
    res.status(500)
            .send("Oops. Something is on fire.");
}

Although express.js provides centralized error handling, it still lacks flexibility due to its over-centralization. Which error handling method you would choose is totally up to you, yet express.js used in this case is only for demonstration.

const express = require("express");
const app = express();
... ... // Set up the app

app.post("/api/boopybot", errorsIn(async (req, res) => {

    // A TypeError will be thrown if body parser is missing
    if (req.body.userId === "honeybadger") {
        res.send("Beep boop, boop beep.");
    } else {
        res.send("Beep beep, beep boop.");
    }

}).willBeCaughtBy(catcher));

Not built specifically for express.js, errorsIn can be used in any case where the error handling mechanism is poorly structured.

Async and When Will It

The wrapped function will return a promise behaves the same as sync but in promises when it reaches any promise-returning middleware, which can be either an async function or an async catcher.

const run = errorsIn(func)
    .willBeCaughtBy(catcher1)
    // ↓ Returns a Promise responsible for the rest catchers
    .and(/*async*/ catcher2) 
    .and(catcher3);

// Successful Return at func:     Not Promise
// Successful Return at catcher1: Not Promise
// Successful Return at catcher2: A Promise
// Successful Return at catcher3: A Promise
const result = /*await*/ run(); 

Context

It's sometimes frustrating when the error is oversimplified. That's when you need some context. The context object can provides what you need.

const contextOf = errorsIn.contextOf;

const run = errorsIn(($var, id) => {
    $var.name = database.get(id, "name");

    if (hasSpecialCharacter($var.name)) 
        throw "I'm the Baaaaad error. Duh.";

}).withContext().willBeCaughtBy((err, id) => {

    const $var = contextOf(err);

    if ($var.name.contains("*")) 
        console.log("Asterisk is not allowed in names.");
});

When specifying with .withContext(), a context object, which is a blank object that can be shared between the function and catchers, will be passed as the first argument. There's also .withoutContext(), which does the opposite to .withContext(). By default, the context is not used, and you have to specify it.

You can acquire the context object in error catchers by using contextOf(err). The context object will be unavailable by calling this function after all catchers have done their job. However, you can still acquire it by setting variable outside or return it.

let context;

const catcher = err => {
    const $var = contextOf(err);
    context = $var; // DIRTY!
    // Or better
    return { context: $var, error: err };
}

It's not necessary to name the context object $var, but you can make it look more natural by doing this, as if you're dealing with variables.

Where is the documentation?

Since I just came up with it, the documentation is work in progress and soon will be online alongside with a git repository. Sorry for the inconvenience.

Dependencies (0)

    Dev Dependencies (2)

    Package Sidebar

    Install

    npm i errors-in

    Weekly Downloads

    3

    Version

    1.2.1

    License

    MIT

    Unpacked Size

    13.9 kB

    Total Files

    4

    Last publish

    Collaborators

    • beavr