[Ramda] Handle Errors in Ramda Pipelines with tryCatch

Handling your logic with composable functions makes your code declarative, leading to code that's easy to read and easy to test. Breaking that up to wrap some risky function in a try/catch block introduces imperative code and makes it harder to maintain that declarative approach. With Ramda's tryCatch function, you can handle errors right in the middle of a composition and leave your code clean and functional. We'll also see how you can use propOr to avoid common "cannot find X of undefined" errors.

 

复制代码
const R = require('ramda');

const person = {
    id: 1,
    name: 'Joe'
};

/*
* The problem for this code:
* R.prop('name') assume that the object passed in has 'name' prop
* But what if the object is undefined? Then we will get error.
*
* Solution: R.tryCatch()
* */
/*
const getPersonName = R.prop('name');
const getUpperCaseName = R.pipe(
    getPersonName,
    R.toUpper
);
const res = getUpperCaseName(person); // ERROR
*/

const getPersonName = R.tryCatch(R.prop('name'), R.always('Default'));
const getUpperCaseName = R.pipe(
    getPersonName,
    R.toUpper
);
const res = getUpperCaseName(undefined);  // DEFAULT


console.log(res);
复制代码

 

Github

posted @   Zhentiw  阅读(427)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-02-17 [Regular Expressions] Match the Start and End of a Line
2016-02-17 [ES7] Object.observe + Microtasks
点击右上角即可分享
微信分享提示