# sentry 前端接入


## 1. 在sentry创建项目
创建项目后会得到 dns

## 2. 安装 SDK
新建完项目后，就会生成一个 DSN，它是和 Sentry 服务通信的唯一标志，稍后我们在项目中进行配置，首先需要在项目中安装 SDK：

```
# Using yarn
$ yarn add @sentry/browser

# Using npm
$ npm install @sentry/browser
```

## 3. 新建 sentryUtil.js 封装公用方法
```javascript
import * as Sentry from '@sentry/browser';

/**
 *  初始化 sentry
 */
function initSentry() {
    Sentry.init({
        dsn: 'http://85ad42f93d7942da88211cf650ee4afd@localhost:9001/2',
    });
}


/**
 *  发送错误信息到 sentry平台 并且返回错误的id 
 */
function sendError(error, errorInfo) {
    let eventId = null;
    Sentry.withScope(scope => {
        scope.setExtras(errorInfo);
        eventId = Sentry.captureException(error);
    });
    return eventId;
}

export {
  initSentry,
  sendError,
}
export default {
  initSentry,
  sendError,
};
```

## 4 在react中使用 
在 react项目 入口组件(最外层的组件)中使用 componentDidCatch 生命周期做错误监控 然后调用 sendError 函数
```javascript
import React from 'react';
import { sendError } from '@/utils/sentryUtil';

export default class BasicLayout extends React.Component {
  // react捕获全局错误
  componentDidCatch(error, errorInfo) {
    // 将错误信息传递到 sentry平台 （监控到错误自动上报）
    sendError(error, errorInfo);
  }
  render() {
    return (
        <div>{this.props.children}</div>
    );
  }
}
```

## 5 高级用法 (可选)
除了自动上报，还可以通过Sentry.captureMessage 手动进行上报:
```javascript
import React from "react";
import * as Sentry from "@sentry/browser";

const Index = () => (
  <div className="Index">
    <button 
      type="button" 
      onClick={() => {
          Sentry.captureMessage("Something went wrong")
      }}
    >
      Capture
    </button>
  </div>
);
```

## 更多内容

https://www.npmjs.com/package/@sentry/browser