gpt4 book ai didi

reactjs - 如何将 Create React App Production Error Boundary 映射到源代码

转载 作者:行者123 更新时间:2023-12-03 13:43:54 25 4
gpt4 key购买 nike

我正在使用错误边界组件来捕获 react 错误,并且它工作正常。

我的问题是,在生产应用程序中,日志记录有点无用,因为组件堆栈如下所示:

\n    in t\n    in t\n   in t\n    in t\n    in t\n    in div\n    in t\n    in u\n    in n\n    in t\n    in t

在开发环境中,组件堆栈更有用:

in ErrorPage (created by Route)\n    in Route (at Routes.js:60)\n    in Switch (at Routes.js:46)\n    in Router (created by BrowserRouter)\n    in BrowserRouter (at Routes.js:45)\n    in div (at Routes.js:43)\n    in ThemeProvider (at theme.js:1262)\n    in Theme (at Routes.js:42)\n    in Provider (at Routes.js:41)\n    in ErrorBoundary (at Routes.js:40)\n    in Routes (at index.js:12)

同样的情况也发生在消息上。在生产中我们得到:

t.value (http://localhost:3333/static/js/main.5a3e606e.js:1:680858

在开发过程中:

Uncaught TypeError: Person is not a constructor
at ErrorPage._this.click2 (ErrorPage.js:12)

有没有办法使 react 错误映射到源代码并使日志记录在生产中实际可用?

更新:我正在使用一个名为 http://js.jsnlog.com/ 的库它处理日志并实际上捕获所有内容(甚至事件处理程序)。这就是边界组件的样子 https://pastebin.com/aBFtD7DB 。问题不在于捕获错误,而在于它们在生产中毫无用处。

最佳答案

我使用库 https://www.stacktracejs.com/ 找到了解决方案。

StackTrace.report() 方法将获取 map 并为您提供所需的完整信息!

现在我的 React 边界看起来像这样。我仍然使用 window.onerror 来确保捕获所有内容。

首先,确保将 stacktrace-gpsstacktrace-js 添加到您的 package.json

import React, { Component } from "react";
import StackTrace from "stacktrace-js";

window.onerror = function(msg, file, line, col, error) {
StackTrace.fromError(error).then(err => {
StackTrace.report(
err,
`//${window.location.hostname}:${process.env.REACT_APP_LOGGER_PORT || 3334}/jsnlog.logger`,
{
type: "window.onerror",
url: window.location.href,
userId: window.userId,
agent: window.navigator.userAgent,
date: new Date(),
msg: msg
}
);
});
};

class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null };
}

componentDidCatch(error, errorInfo) {
this.setState({ error });
StackTrace.fromError(error).then(err => {
StackTrace.report(
err,
`//${window.location.hostname}:${process.env.REACT_APP_LOGGER_PORT || 3334}/jsnlog.logger`,
{
type: "React boundary",
url: window.location.href,
userId: window.userId,
agent: window.navigator.userAgent,
date: new Date(),
msg: error.toString()
}
);
});
}

render() {
if (this.state.error) {
//render fallback UI
return (
<div className="snap text-center">
<p>We're sorry — something's gone wrong.</p>
<p>Our team has been notified</p>
</div>
);
} else {
//when there's not an error, render children untouched
return this.props.children;
}
}
}

export default ErrorBoundary;

关于reactjs - 如何将 Create React App Production Error Boundary 映射到源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50223991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com