[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 ...
随机推荐
- 洛谷P2507 [SCOI2008]配对 [DP,贪心]
题目传送门 配对 题目描述 你有 n 个整数Ai和n 个整数Bi.你需要把它们配对,即每个Ai恰好对应一个Bp[i].要求所有配对的整数差的绝对值之和尽量小,但不允许两个相同的数配对.例如A={5,6 ...
- SpringBoot学习(三)
一.单个 controller 范围的异常处理 package com.xxx.secondboot.web; import org.springframework.web.bind.annotati ...
- codevs 1230【pb_ds】
题目链接[http://codevs.cn/problem/1230/] 题意:给出n个正整数,然后有m个询问,每个询问一个整数,询问该整数是否在n个正整数中出现过. 题解:很简单的一道题,可以选择用 ...
- 【随机化】【并查集】Gym - 100851J - Jump
题意:交互题,有一个长度为n(偶数)的二进制串,你需要猜不超过n+500次猜到它.如果你猜的串与原串相同的位数为n,那么会返回n,如果为n/2,那么会返回n/2,否则都会返回零. 先random,直到 ...
- nginx-404与fastcgi_intercept_errors指令
nginx-404与fastcgi_intercept_errors指令 fastcgi_intercept_errors语法:fastcgi_intercept_errors on|off 默认值: ...
- Java并发(十):读写锁ReentrantReadWriteLock
先做总结: 1.为什么用读写锁 ReentrantReadWriteLock? 重入锁ReentrantLock是排他锁,在同一时刻仅有一个线程可以进行访问,但是在大多数场景下,大部分时间都是提供读服 ...
- hdu 1711
读入优化有3s多. #include <cstdio> #include <cctype> #define maxn 1000010 #define maxm 10010 in ...
- NOIP200606金明的预算方案
试题描述: 金明今天很开心,家里购置的新房就要领钥匙了,新房里有一间金明自己专用的很宽敞的房间.更让他高兴的是,妈妈昨天对他说:“你的房间需要购买哪些物品,怎么布置,你说了算,只要不超过N元钱就行”. ...
- [转]Android应用中返回键的监听及处理
用户在点击手机的返回按钮时,默认是推出当前的activty,但是有时用户不小心按到返回,所以需要给用户一个提示,这就需要重写onkeydown事件,实现的效果如下: 标签: Android ...
- Eclipse打开.class文件
1.准备材料 jad.exe 下载地址 https://varaneckas.com/jad/,根据系统去选择(就当是废话) 下载下来的是jad158g.win.zip压缩文件,解压后有个j ...