In Error handling we have two possible paths either a computation succeeds or fails. The imperative way to control the flow is using exceptions and a try/catch block. In functional programming they recognized that those two paths ok or error can be joined into a structure that signifies one or the other as a possibility and so we can unify them into an Either <ok,error> structure.

Either is a common type in functional Languages. Is commonly called a discriminated union. Which means an Either type can contain any of the types it sums up.

In order to find out whats inside the Either we pattern match. Usually in most functional libraries there would be a method that is called cata (also match or matchWith) that does exactly than :

Ok, Lets move one to how we could use it in error handling. The important thing in either Functor implementation is that by convention the left when mapped just ignores the mapping .

const right = (v) => ({

map: (f) => right(f(v)),

});



const left = (v) => ({

map: (_) => left(v),

});

this means that when we return a left then no more computations are executed with map.

Refactoring Try / catch to Either

lets say we have this try catch block

var finalPrice;

try {

var discount = 0.1;

finalPrice = 10 - discount * 10;

} catch (e) {

console.log(e);

} if (finalPrice) {

console.log(finalPrice);

}

we want to remove the try/catch from the actual computations .

try {

var computation = () => {

var discount = 0.1;

var finalPrice = 10 - discount * 10;

return finalPrice;

}

} catch (e) {

console.log(e);

}

then we extract a method and pass the computation as a parameter

var Try = (f) => {

try {

return f();

} catch (e) {

console.log(e);

}

} var finalPrice = Try(() => {

var discount = 0.1;

var finalPrice = 10 - discount * 10;

return finalPrice;

});

and finally we return an Either like that