代码整洁之道——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!
  });

 

posted on 2017-07-27 11:01  小小驰  阅读(389)  评论(0编辑  收藏  举报