zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    什么是Servlet
    Linux进程创建、执行和切换过程理解
    java实现验证码登录
    jsp页面如何动态显示当前时间
    java容器的一些存取用法
    java内存的那些事
    eclipse的常用快捷键
    二叉树前序、中序、后序遍历相互求法
    二叉树的遍历
    jsp添加背景音乐
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6411193.html
Copyright © 2011-2022 走看看