纯错误处理

最后更新于:2022-04-02 04:17:56

[TOC] ## “纯”错误处理 - `throw/catch`并不十分“纯” - 可以使用`Either` 处理纯函数 ``` var Left = function(x) { this.__value = x; } Left.of = function(x) { return new Left(x); } Left.prototype.map = function(f) { return this; } var Right = function(x) { this.__value = x; } Right.of = function(x) { return new Right(x); } Right.prototype.map = function(f) { return Right.of(f(this.__value)); } ``` Left 和 Right 是我们称之为 Either 的抽象类型的两个子类 实例 ``` var moment = require('moment'); // getAge :: Date -> User -> Either(String, Number) var getAge = curry(function(now, user) { var birthdate = moment(user.birthdate, 'YYYY-MM-DD'); if(!birthdate.isValid()) return Left.of("Birth date could not be parsed"); return Right.of(now.diff(birthdate, 'years')); }); getAge(moment(), {birthdate: '2005-12-12'}); // Right(9) getAge(moment(), {birthdate: 'balloons!'}); // Left("Birth date could not be parsed") ```
';