[JS Compose] 3. Use chain for composable error handling with nested Eithers (flatMap)
We refactor a function that uses try/catch to a single composed expression using Either. We then introduce the chain function to deal with nested Eithers resulting from two try/catch calls.
For example we have this code using try & catch:
const getPort = () => {
try {
const file = fs.readFileSync('config.json');
const c = JSON.parse(file);
return c.port;
} catch(e) {
return ;
}
}
And now, we want to use Either to rewirte the code:
// SETUP: fake fs
//==========
const fs = {
readFileSync: name => {
if(name === 'config.json') {
return JSON.stringify({port: })
} else {
throw('missing file!')
}
}
} //================= const Right = x => ({
map: f => Right(f(x)),
fold: (f, g) => g(x),
toString: () => `Right(${x})`
}); const Left = x => ({
map: f => Left(x),
fold: (f, g) => f(x),
toString: () => `Left(${x})`
}); const fromNullable = x =>
x != null ? Right(x): Left(null); const tryCatch = f => {
try {
return Right(f());
} catch(e) {
return Left(e);
}
} //=========================
const getPort = () =>
tryCatch(() => fs.readFileSync('config.json'))
.map(f => JSON.parse(f))
.fold(
x => ,
x => x.port); console.log(getPort('config.json'))
We wrote the function 'tryCatch', the idea is put the code need to be checked in try, when success call 'Right', error, call 'Left()'.
tryCatch(() => fs.readFileSync('config.json'))
Read the file, is success, will return file content. If not, then goes to set default 3000.
.fold(
x => ,
x => x.port);
It works, but we still miss one things, in the old code, the 'JSON.parse' are also wrapped into try catch.
const getPort = () =>
tryCatch(() => fs.readFileSync('config.json')) //Right('{port:8888}')
.map(f => tryCatach(() => JSON.parse(f))) //Right(Right({port:8888}))
But once we also wrap parseing code into tryCatch function, the return value is 2d-Right. So we want to flatten it.
const Right = x => ({
map: f => Right(f(x)),
flatMap: f => f(x),
fold: (f, g) => g(x),
toString: () => `Right(${x})`
}); const Left = x => ({
map: f => Left(x),
flatMap: f => f(x),
fold: (f, g) => f(x),
toString: () => `Left(${x})`
});
We add 'flatMap', so instead of putting the value into Right() or Left(), we just return the value. Because we know the value passed in is already a Right or Left.
const getPort = () =>
tryCatch(() => fs.readFileSync('config.json')) //Right('{port:8888}')
.flatMap(f => tryCatch(() => JSON.parse(f))) //Right({port:8888})
.fold(
x => ,
x => x.port);
---------
// SETUP: fake fs
//==========
const fs = {
readFileSync: name => {
if(name === 'config.json') {
return JSON.stringify({port: })
} else {
throw('missing file!')
}
}
} //================= const Right = x => ({
map: f => Right(f(x)),
flatMap: f => f(x),
fold: (f, g) => g(x),
toString: () => `Right(${x})`
}); const Left = x => ({
map: f => Left(x),
flatMap: f => f(x),
fold: (f, g) => f(x),
toString: () => `Left(${x})`
}); const fromNullable = x =>
x != null ? Right(x): Left(null); const tryCatch = f => {
try {
return Right(f());
} catch(e) {
return Left(e);
}
} //=========================
const getPort = () =>
tryCatch(() => fs.readFileSync('config.json')) //Right({port:8888})
.flatMap(f => tryCatch(() => JSON.parse(f))) //Right(Right({port:8888}))
.fold(
x => ,
x => x.port); console.log(getPort('config.json'))
-----
You can also rename 'flatMap' to 'chain'. Sometime 'flatMap' or 'chain' looks similar to 'fold' implementation. But the meaning is different, here 'chain / flatMap' says It says, "If we're going to return another Either
, we are going to use chain
instead of map." 'fold' says just get the value out of the box, it's done!
[JS Compose] 3. Use chain for composable error handling with nested Eithers (flatMap)的更多相关文章
- JS function document.onclick(){}报错Syntax error on token "function", delete this token
JS function document.onclick(){}报错Syntax error on token "function", delete this token func ...
- JS function document.onclick(){}报错Syntax error on token "function", delete this token - CSDN博客
原文:JS function document.onclick(){}报错Syntax error on token "function", delete this token - ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions
The ideal time to catch an error is at compile time, before you even try to run the program. However ...
- Erlang error handling
Erlang error handling Contents Preface try-catch Process link Erlang-way error handling OTP supervis ...
- MySQL Error Handling in Stored Procedures 2
Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered ...
- setjmp()、longjmp() Linux Exception Handling/Error Handling、no-local goto
目录 . 应用场景 . Use Case Code Analysis . 和setjmp.longjmp有关的glibc and eglibc 2.5, 2.7, 2.13 - Buffer Over ...
- Error Handling
Use Exceptions Rather Than Return Codes Back in the distant past there were many languages that didn ...
- Error Handling and Exception
The default error handling in PHP is very simple.An error message with filename, line number and a m ...
- Clean Code–Chapter 7 Error Handling
Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...
随机推荐
- 洛谷P3434 [POI2006]KRA-The Disks [模拟]
题目传送门 KRA 题目描述 For his birthday present little Johnny has received from his parents a new plaything ...
- Python函数系列-一个简单的生成器的例子
def consumer(): while True: x = yield print('处理了数据:',x) def producer(): pass c = consumer() #构建一个生成器 ...
- SpringMVC框架 注解 (转)
原文地址:http://www.cnblogs.com/yjq520/p/6734422.html 1.@Controller @Controller 用于标记在一个类上,使用它标记的类就是一个Spr ...
- FastReport.Net使用:[9]多栏报表(多列报表)
方法一:使用页的列属性(Page Columns) 1.绘制报表标题 2.设置页的列数量为3,其他默认不变.报表设计界面便如下呈现. 3.报表拷贝前面[分组]报表的内容. 4.就这么简单,一张多栏报表 ...
- SPOJDRUIDEOI - Fata7y Ya Warda!【单调栈】
题目链接[http://www.spoj.com/problems/DRUIDEOI/en/] 题意:给出n个数,从1到n围城一个环(1和n相连),求每个数左边第一个比他大的第一个下标,右边第一个比他 ...
- BZOJ [JSOI2008]星球大战starwar
正着显然不可做,我们采取反向并查集,将删点改为加点,每次贪心的认为加了一个联通块,一旦不符就减一. #include<bits/stdc++.h> using namespace std; ...
- 51nod1203 JZPLCM 线段树 + 扫描线
不算很难的一道题 原题的数据虽然很小,但是我们不能欺负它,我们就要当$S[i] \leqslant 10^9$来做这题 最小公倍数 = 所有的质因数取可能的最大幂相乘 对于$> \sqrt S$ ...
- 【二分答案】【DFS】【分类讨论】Gym - 100851F - Froggy Ford
题意:河里有n块石头,一只青蛙要从左岸跳到右岸,你可以再在任意一个位置放一块石头,使得在最优方案下,青蛙单步跳的距离的最大值最小化,输出该位置. 将原图视作完全图,二分答案mid,然后在图中只保留小于 ...
- poj 1703 并查集
题意:在这个城市里有两个黑帮团伙,现在给出N个人,问任意两个人他们是否在同一个团伙 输入D x y代表x于y不在一个团伙里 输入A x y要输出x与y是否在同一团伙或者不确定他们在同一个团伙里 链接: ...
- Spark参数配置总结