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:

Implementing Infinite Scroll In Next Js With Server Actions

Implementing infinite scroll in Next.js with Server Actions

Infinite scrolling in Next.js no longer requires external libraries — Server Actions let us fetch initial data directly on the server.

Rahul Chhodde
Apr 19, 2024 ⋅ 10 min read
Integrating Django Templates With React For Dynamic Webpages

Integrating Django templates with React for dynamic webpages

Create a dynamic demo blog site using Django and React to demonstrate Django’s server-side functionalities and React’s interactive UI.

Kayode Adeniyi
Apr 18, 2024 ⋅ 7 min read
Using Aoi Js To Build A Bot For Discord

Using aoi.js to build a bot on Discord

Explore how the aoi.js library makes it easy to create Discord bots with useful functionalities for frontend applications.

Rahul Padalkar
Apr 17, 2024 ⋅ 9 min read
Web Components Adoption Guide: Overview, Examples, And Alternatives

Web Components adoption guide: Overview, examples, and alternatives

Evaluate Web Components, a set of standards that allow you to create custom HTML tags for more reusable, manageable code.

Elijah Asaolu
Apr 16, 2024 ⋅ 11 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