# 异常监控

* 前端错误的分类
* 错误的捕获方式
* 上报错误的基本原理

## 1、前端错误的分类

* 即时运行错误：代码错误
* 资源加载错误

## 2、错误的捕获方式

### 即时运行错误捕获方式

1. try...catch&#x20;
2. window\.onerror

### 资源加载错误

1. object.onerror&#x20;
2. performance.getEntries&#x20;
3. Error事件捕获

* 资源加载错误事件不会冒泡，只会在本身这个object报错事件进行响应
* performace.getEntries()这个API获取所有资源的加载地址

![](/files/-MGDQSIz6hwLnj4IG-g6)

* Error事件捕获

```markup
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script type="text/javascript">
      window.addEventListener('error',function (e) {
        console.log('捕获',e);
      }, true);
    </script>
    <script src="/js/index.js" charset="utf-8"></script>
  </body>
</html>
```

![](/files/-MGDQSJ-5RW0jIlB1lh7)

### 跨域资源加载错误

1. 在script标签增加crossorigin属性（客户端错误）
2. 设置JS资源响应头Access-Control-Allow-Origin:\*（服务端做）

## 3、错误监控

* 上报错误的基本原理
  * 使用Ajax通信进行上报
  * 利用Image对象上报

```markup
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script type="text/javascript">
      window.addEventListener('error',function (e) {
        console.log('捕获',e);
      }, true);
    </script>
    <script src="/js/index.js" charset="utf-8"></script>
    <script type="text/javascript">
      let errors = 'imgerror';
      (new Image()).src = `http://www.kejiganhuo.com/test?error=${errors}`;
    </script>
  </body>
</html>
```

![](/files/-MGDQSJ033HAf-ADBfpA)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jonathan-zhang.gitbook.io/javascript-steppitguide/jin-jie-zhi-shi/17.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
