Skip to content

错误处理

抛出的错误是好事!这表明运行时已成功识别程序中存在的问题,它会通过终止当前堆栈函数执行、终止进程(Node环境下),并在控制台输出带堆栈跟踪的错误信息。这能让程序问题有效暴露,而不是隐匿在正常流程中。

不要忽略已捕获的错误

对捕获的错误放任不管将使您失去修复或响应的机会。仅使用console.log记录错误并非良策,因为这类信息容易淹没在海量控制台输出中。当用try/catch包裹代码段时,意味着您已预见潜在错误,因此应当制定处理计划或创建特定的代码处理路径。

反例:

javascript
try {
  functionThatMightThrow();
} catch (error) {
  console.log(error);
}

正例:

javascript
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!
}

不要忽略被拒绝的Promise

这与不应忽略try/catch捕获错误的原因一致

反例:

javascript
getdata()
  .then(data => {
    functionThatMightThrow(data);
  })
  .catch(error => {
    console.log(error);
  });

正例:

javascript
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!
  });