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:

How To Create Heatmaps In Javascript: Exploring The Heat Js Library

How to create heatmaps in JavaScript: The Heat.js library

This tutorial will explore the application of heatmaps in JavaScript projects, focusing on how to use the Heat.js library to generate them.

Oghenetega Denedo
May 8, 2024 ⋅ 7 min read
Eleventy Adoption Guide: Overview, Examples, And Alternatives

Eleventy adoption guide: Overview, examples, and alternatives

Eleventy (11ty) is a compelling solution for developers seeking a straightforward, performance-oriented approach to static site generation.

Nelson Michael
May 7, 2024 ⋅ 8 min read
6 CSS Tools For More Efficient And Flexible CSS Handling

6 CSS tools for more efficient and flexible CSS handling

Explore some CSS tools that offer the perfect blend of efficiency and flexibility when handling CSS, such as styled-components and Emotion.

Fimber Elemuwa
May 7, 2024 ⋅ 7 min read
Leveraging React Server Components In Redwoodjs

Leveraging React Server Components in RedwoodJS

RedwoodJS announced support for server-side rendering and RSCs in its Bighorn release. Explore this feature for when it’s production-ready.

Stephan Miller
May 6, 2024 ⋅ 9 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