Skip to content

JS 错误捕捉

Published: at 02:21 PMSuggest Changes

简单记一下,前端错误捕捉。

代码

一般事件异常捕捉

window.onerror = function (message, source, lineno, colno, error) {
  console.log('捕获到异常:', { message, source, lineno, colno, error });
};

资源加载异常捕捉

<script>
  function errorHandler(error) {
    console.log('捕获到静态资源加载异常', error);
  }
</script>
<script
  src="http://cdn.xxx.com/js/test.js"
  onerror="errorHandler(this)"
></script>
<link
  rel="stylesheet"
  href="http://cdn.xxx.com/styles/test.css"
  onerror="errorHandler(this)"
/>

全局异常捕捉

window.addEventListener(
  'error',
  (error) => {
    console.log('捕获到异常:', error);
  },
  true
);

Promise 异常捕捉

window.addEventListener("unhandledrejection", function (e) {
  e.preventDefault();
  console.log("捕获到 promise 错误了");
  console.log("错误的原因是", e.reason);
  console.log("Promise 对象是", e.promise);
  return true;
});

Promise.reject("promise error");
new Promise((resolve, reject) => {
  reject("promise error");
});
new Promise((resolve) => {
  resolve();
}).then(() => {
  throw "promise error";
});

后记

参考文章


Previous Post
MySQL 删除表
Next Post
JS XHR 拦截