loading...

re: Handling errors with Either VIEW POST

FULL DISCUSSION
 

Hi! Nice article. I have been using vavr and its Either type for a while. I still didn't quite figure out how to use it when I need to expose different type of errors in the either. I thought about have different Error type and do a type assertion, but at this point I d better go with exceptions which expose this behaviour naturally(catch clauses with different types). Do you have any thought about it?

 

Well, if you actually need different behaviour for different kinds of errors (as opposed to simply having different data in the error), you need a bit of extra effort to make it work with Either. I don't know about vavr, but it seems to be Java, and Java has a pretty decent exception system, so the easiest might be to just throw and catch checked exceptions.

That being said, Elm has a cool thing called union types which can be used to handle multiple kinds of errors. It's similar to an Either, but it allows more than two branches, each branch with a different behaviour.

To implement that in Javascript I would try something like this:

const UnionType = types => types.reduce((prev, type) => ({
    ...prev,
    [type]: (data) => ({
        match: (fns) => fns[type](data)
    })
}), {})

Then you can create your own union type to handle errors.

const CustomErrors = UnionType([
    'NetworkError',
    'InputError',
    'RandomError',
])

const someError = CustomErrors.RandomError({ message: 'Random' })

someError.match({
    NetworkError: ({ status, message }) => {...},
    InputError: ({ field, value }) => {...},
    RandomError: ({ message }) => console.error(message),
})

You can either have a union type in the left branch of an Either and do the matching when you fold it, or have a union type with a branch for valid values and several branches for invalid values (not sure how that second option would work out, though, you would need to implement map and chain in UnionType also). And, of course, you can use it for a lot of other things, besides handling different kinds of errors.

Now, this is something I just thought that might be interesting to borrow from Elm, but I haven't really tried in Javascript, so use it with caution.

 

Interesting! Gotta read about union types and experiment a bit. Thanks a lot :)

You're welcome, I hope you find it useful! :)

Code of Conduct Report abuse