Skip to main content

js错误处理

window.onerror

该方法可以捕获所有未被捕获的 JavaScript 异常,并将其作为参数传递给处理程序函数。

要在项目中使用 window.onerror 方法,您需要在全局范围内定义该方法。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Website</title>
<script>
window.onerror = function(message, url, line, column, error) {
console.log('发生了异常:' + message);
console.log('在文件 ' + url + ' 的第 ' + line + ' 行,第 ' + column + ' 列');
console.log('错误对象:', error);
};
</script>
</head>
<body>
<!-- 页面内容 -->
<script src="main.js"></script>
</body>
</html>

react函数组件实现的错误边界

import React, { useState, useEffect } from 'react';

function ErrorBoundary({ children }) {
const [hasError, setHasError] = useState(false);

useEffect(() => {
const handleErrors = (error, info) => {
// 在这里处理异常
console.log('发生了异常:' + error);
console.log('堆栈信息:' + info.componentStack);
setHasError(true);
};
window.addEventListener('error', handleErrors);
return () => window.removeEventListener('error', handleErrors);
}, []);

if (hasError) {
// 在这里呈现备用 UI
return <h1>发生了错误</h1>;
}
return children;
}

export default ErrorBoundary;

使用:

import React from 'react';
import ErrorBoundary from './ErrorBoundary';

function MyComponent() {
// 在这里定义组件
}

export default function App() {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
}

react17在类组件中

使用 static getDerivedStateFromError() 和 componentDidCatch() 方法来代替 componentDidCatch() 方法来处理错误:

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

static getDerivedStateFromError(error) {
return { hasError: true, error: error };
}

componentDidCatch(error, errorInfo) {
console.error(error, errorInfo);
this.setState({ errorInfo: errorInfo });
}

render() {
if (this.state.hasError) {
return (
<div>
<h1>Oops! Something went wrong.</h1>
<p>{this.state.error && this.state.error.toString()}</p>
<p>{this.state.errorInfo.componentStack}</p>
</div>
);
}

return this.props.children;
}
}

class App extends React.Component {
render() {
return (
<div>
<ErrorBoundary>
<App />
</ErrorBoundary>
</div>
);
}
}