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:

Nx Adoption Guide: Overview, Examples, And Alternatives

Nx adoption guide: Overview, examples, and alternatives

Let’s explore Nx features, use cases, alternatives, and more to help you assess whether it’s the right tool for your needs.

Andrew Evans
Mar 28, 2024 ⋅ 9 min read
Understanding Security In React Native Applications

Understanding security in React Native applications

Explore the various security threats facing React Native mobile applications and how to mitigate them.

Wisdom Ekpotu
Mar 27, 2024 ⋅ 10 min read
Warp Adoption Guide: Overview, Examples, And Alternatives

warp adoption guide: Overview, examples, and alternatives

The warp web framework for Rust offers many enticing features. Let’s see when and why you should consider using warp in your projects.

Ukeje Goodness
Mar 26, 2024 ⋅ 8 min read
Integrating Next Js And Signalr For Enhanced Real Time Web App Capabilities

Integrating Next.js and SignalR to build real-time web apps

In this tutorial, you’ll learn how to integrate Next.js and SignalR to build an enhanced real-time web application.

Clara Ekekenta
Mar 25, 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