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:

Understanding The Css Revert Layer Keyword, Part Of Css Cascade Layers

Understanding the CSS revert-layer keyword

In this article, we’ll explore CSS cascade layers — and, specifically, the revert-layer keyword — to help you refine your styling strategy.

Chimezie Innocent
Apr 24, 2024 ⋅ 6 min read
Exploring Nushell, A Rust Powered, Cross Platform Shell

Exploring Nushell, a Rust-powered, cross-platform shell

Nushell is a modern, performant, extensible shell built with Rust. Explore its pros, cons, and how to install and get started with it.

Oduah Chigozie
Apr 23, 2024 ⋅ 6 min read
Exploring Zed, A Newly Open Source Code Editor Written In Rust

Exploring Zed, an open source code editor written in Rust

The Zed code editor sets itself apart with its lightning-fast performance and cutting-edge collaborative features.

Nefe Emadamerho-Atori
Apr 22, 2024 ⋅ 7 min read
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
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