zoukankan      html  css  js  c++  java
  • 代码整洁之道——8、错误处理

    抛出错误是一个很好的事情。这意味着当你的程序出错的时候可以成功的知道,并且通过停止当前堆栈上的函数来让你知道,在node中会杀掉进程,并在控制套上告诉你堆栈跟踪信息。

    一、不要忽略捕获的错误

    不处理错误不会给你处理或者响应错误的能力。经常在控制台上打印错误不太好,因为打印的东西很多的时候它会被淹没。如果你使用try/catch这意味着你考虑到这里可能会发生错误,所以对将出现的错误你应该有个计划,或者创建代码路径

    Bad:
    //出现错误只记录
    try {
      functionThatMightThrow();
    } catch (error) {
      console.log(error);
    }
    
    
    Good:
    //出现错误提供解决方案
    try {
      functionThatMightThrow();
    } catch (error) {
      // One option (more noisy than console.log):
      console.error(error);
      // Another option:
      notifyUserOfError(error);
      // Another option:
      reportErrorToService(error);
      // OR do all three!
    }

    二、不要忽略被拒绝的promises

    与不应该忽略try/catch 错误的原因相同

    Bad:
    getdata()
      .then((data) => {
        functionThatMightThrow(data);
      })
      .catch((error) => {
        console.log(error);
      });
    
    Good:
    getdata()
      .then((data) => {
        functionThatMightThrow(data);
      })
      .catch((error) => {
        // One option (more noisy than console.log):
        console.error(error);
        // Another option:
        notifyUserOfError(error);
        // Another option:
        reportErrorToService(error);
        // OR do all three!
      });
  • 相关阅读:
    Shell脚本sed命令
    Shell脚本常用unix命令
    Shell的case语句
    3.5.2 数值之间的转换
    3.5.1 数学函数与常量
    3.5 运算符
    3.4.2 常量
    3.4.1 变量初始化
    3.4 变量
    Python异常捕捉的一个小问题
  • 原文地址:https://www.cnblogs.com/xxchi/p/7243692.html
Copyright © 2011-2022 走看看