前端错误捕获方法

4 阅读1分钟

1 try...catch 语句:用于捕获同步代码中的错误。

try {
  // 可能会出错的代码
  const result = someFunctionThatMightError();
} catch (error) {
  // 处理错误
  console.error(error);
}

2 window.onerror 事件:用于捕获全局未捕获的 JavaScript 运行时错误。

window.onerror = function(message, source, lineno, colno, error) {
  console.error('全局错误:', message, source, lineno, colno, error);
};

3 Promise 的错误捕获,有以下几种方式:

3.1 使用 .then 和 .catch 方法:

promise
 .then(result => {
    // 处理成功的结果
  })
 .catch(error => {
    // 处理错误
    console.error(error);
  });

3.2 使用 async/await 时,通过 try...catch 捕获:

async function myFunction() {
  try {
    const result = await promise;
    // 处理成功的结果
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}