头图

How to track online errors

xiaohuoni
中文

Recap

This problem has been encountered since the first project I took over. At that time, I was still an intern in the game group. I listened to the yelling of the front-end team next door. Why did some users react to what went wrong? What happened? Can't use it again.

The little programmer said calmly: "What browser does the user use? How to reproduce it?".

This problem is relatively common for programmers, and it may be difficult to understand subconsciously, but there are users who do not know what browser they are using. Then the customer service went to communicate with the user.

User feedback: "Ah, it's not the browser that comes with the phone!"

Programmer: "What phone does he use? What version, Android or ios, and how many versions of Android? What did he do before the error occurred?"

Customer Service: "?"
user:"?"

Interestingly, this issue was communicated back and forth for two or three days. In the end, because the user was using a mobile phone with a lower Android version, our company could not find a reproduced machine. In the end, the manager who yelled at first said, "Let's talk about it when you find a reproduced mobile phone. Anyway, only this user has encountered this problem."

What happened later, I think everyone is very clear. As long as it is "waiting to do it in the future, subsequent optimization", then basically this demand is killed.

At that time, I was thinking, is it only one cell phone that has problems, or is there a problem with that series of phones? Only this one user encountered this problem, is it really only he encountered the problem, or only he feedback the problem? In fact, for developers, the chance of receiving positive feedback will be much less than the chance of receiving negative feedback. Is there any way to automatically record all the problems encountered by users? Then correctly feed back the data that the programmer needs?

Back to our question, how to track down online errors? Do you know how to track local errors? (When the console is not opened, and there is no debug.)

How to catch program errors?

How to catch js native errors?

This can be regarded as a basic js operation, in fact it is to monitor window.onerror.

<!DOCTYPE html>
<html lang="en">

<head>
  <script>
    window.onerror = function (message, source, lineno, colno, exception) {
      console.log(message);
      console.log(source);
      console.log(lineno);
      console.log(colno);
      console.log(exception);
    }
  </script>
  <script>
    var a -1;
  </script>
</head>

<body>
</body>

</html>

Open the console and you will see this printed information.

Uncaught SyntaxError: Unexpected token '-' 
file:///Users/xiaohuoni/blog/blog/index.html
15
11
SyntaxError: Unexpected token '-'

In addition to common syntax errors, js also provides an event- onunhandledrejection -when the Promise is rejected and there is no reject processor, the unhandledrejection event will be triggered;

<!DOCTYPE html>
<html lang="en">

<head>
  <script>
    window.onerror = function (message, source, lineno, colno, exception) {
      console.log(message);
      console.log(source);
      console.log(lineno);
      console.log(colno);
      console.log(exception);
    }
    window.onunhandledrejection = event => {
      console.warn(`UNHANDLED PROMISE REJECTION: ${JSON.stringify(event.reason)}`);
      event.preventDefault();
    };
  </script>
  <script>
    function myExecutorFunc(resolutionFunc, rejectionFunc) {
      rejectionFunc(777);
    }
    var myPromise = new Promise(myExecutorFunc);
  </script>
</head>

<body>
</body>

</html>
To eliminate the above error, just var myPromise = new Promise(myExecutorFunc).then().catch((data) => console.log(data))

The above method can help us correctly catch the native js error. We only need to send the received data to the remote server through an interface call to view the data in the background.

How to catch errors in react

Some UI JavaScript errors should not cause the entire application to crash. To solve this problem, React 16 introduced a new concept- error boundary .

The following examples can be understood by quoting the official website.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 你同样可以将错误日志上报给服务器
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 你可以自定义降级后的 UI 并渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

We can report the error log to the server here. In this way, we have completed the front-end development of the error log collection service. I hope it will be helpful to friends who want to build an error log platform by themselves.

How to catch online errors

Of course, if you don’t have your own server, or just a small project, you don’t want to spend such a big experience to implement this platform. Now there are many open source platforms in the community to choose from. Here we recommend a sentry . His backend is free and provides a lot of cross-platform access methods, including 97 different platforms such as js, React, React Native and native applications.

If it is a umi project, you can directly use the plug-in @alitajs/sentry .

Add configuration after installation

import { defineConfig } from 'umi';
export default defineConfig({
  plugins: ['@alitajs/sentry'],
  sentry: {
    dsn: '可以访问 https://sentry.io/ 免费申请,记得选 react 项目类型',
  },
});

In this way, you can see the error log and the stack where the error occurred in the background when the project is running. And when an error occurs again, you can also reset the status. For example, in an abnormal situation, the server 504 is down, and you just hang up locally. At this time, the user only needs to click the'reset' button to restore the current running status of the project. It can also be configured to show users a form of user feedback when an error occurs.

Finally, let's briefly demonstrate the backstage of sentry. (In the umi project or the alita project, only simple configuration is required.)

sentry background display

错误跟踪

错误堆栈

Thanks for reading. Any questions can be discussed together in the comments. Friends who like this article, please give a like, friends who like me, can pay attention to me. Thank you Sanlian.

阅读 646
92 声望
0 粉丝
0 条评论
92 声望
0 粉丝
文章目录
宣传栏