2021-09-15
5223
#vanilla javascript
James Sinclair
270
Sep 15, 2021 ⋅ 18 min read

Using the JavaScript Either monad for error handling

James Sinclair I am passionate about functional programming, test-driven development, and continuous delivery. I am also interested in neural networks and deep learning.

Recent posts:

Comparing Hattip Vs Express Js For Modern Application Development

Comparing Hattip vs. Express.js for modern app development

Explore what Hattip is, how it works, its benefits and key features, and the differences between Hattip and Express.js.

Antonello Zanini
May 2, 2024 ⋅ 8 min read
Using React Shepherd To Build A Site Tour

Using React Shepherd to build a site tour

React Shepherd stands out as a site tour library due to its elegant UI and out-of-the-box, easy-to-use React Context implementation.

Onuorah Bonaventure
May 1, 2024 ⋅ 14 min read
A Guide To Cookies In Next Js

A guide to cookies in Next.js

Cookies are crucial to web development. This article will explore how to handle cookies in your Next.js applications.

Georgey V B
Apr 30, 2024 ⋅ 10 min read
Handling Dates In JavaScript With Tempo

Handling dates in JavaScript with Tempo

Use the Tempo library to format dates and times in JavaScript while accounting for time zones, daylight saying time, and date internationalization.

Amazing Enyichi Agu
Apr 30, 2024 ⋅ 8 min read
View all posts

5 Replies to "Using the JavaScript Either monad for error handling"

  1. Honestly I don’t like this approach for handling errors/exceptions, for me it’s better to read this:

    async function read(id, db) {
    let category = null;

    try {
    category = await db.models.Category.findByPk(id);
    } catch (error) {
    return { success: false, data: null, error: error };
    }

    return { success: true, data: category, error: null };
    }

    router.get(‘categories/:id’, function (req, res, next) {
    let result = await read(req.params.id);
    if (result.success) {
    next(result.error);
    } else {
    res.json(result.data);
    }
    });

    Here I’m handling the possible exceptions successfully, the function will always return a value that’s an object with the flag of “success” as true or false to later do the proper work using the data or the error object.

    I see a better error handling there using a procedural style than trying to figure out what a external dependency that have a flat, left, Ap, right, either, chain etc functions will do for me, I don’t see the intentions of the code clearly, in the procedural way I see the solution easy.

    1. Hi James, thanks for pointing that out. I’ve fixed the formatting for the `Left` and `Right` blocks and have done a bit of extra cleanup as well. Cheers

Leave a Reply