答案:通过结合try-catch、window.onerror和unhandledrejection,可全面捕获JavaScript同步异步错误,配合错误上报机制实现前端稳定性监控。

当JavaScript代码运行出错时,如果不加以处理,可能直接导致页面功能失效或用户体验中断。合理地捕获异常并建立监控系统,是保障前端稳定性的关键环节。
JavaScript中常见的错误类型包括SyntaxError、ReferenceError、TypeError等。使用try-catch可以捕获同步代码中的运行时异常。
例如:
try {
someUndefinedFunction();
} catch (error) {
console.error('捕获到错误:', error.message);
}
注意:try-catch无法捕获异步任务中的错误,比如setTimeout内部抛出的异常。
立即学习“Java免费学习笔记(深入)”;
通过监听window.onerror,可以捕获未被处理的JavaScript运行时错误,包括跨域脚本错误(需配合CORS和script标签的crossorigin属性)。
基本写法:
window.onerror = function(message, source, lineno, colno, error) {
console.log('全局错误:', { message, source, lineno, error });
// 上报到服务器
reportErrorToServer({
message: error?.message || message,
stack: error?.stack,
url: source,
line: lineno,
column: colno,
timestamp: Date.now()
});
return true; // 阻止默认错误弹窗
};
该方法能捕获大部分同步错误,但对Promise异常无效。
Promise执行过程中如果未加catch,会触发unhandledrejection事件。务必监听此事件,避免遗漏异步错误。
示例:
window.addEventListener('unhandledrejection', function(event) {
const reason = event.reason;
console.warn('未处理的Promise拒绝:', reason);
reportErrorToServer({
message: reason?.message || 'Unknown Promise rejection',
stack: reason?.stack,
type: 'unhandledrejection',
timestamp: Date.now()
});
// 可选择阻止默认行为
event.preventDefault();
});
这能有效覆盖async/await或链式调用中漏掉catch的情况。
收集错误后,需要将数据发送至监控服务。建议:
简单上报函数:
function reportErrorToServer(data) {
const payload = JSON.stringify(data);
if (navigator.sendBeacon) {
navigator.sendBeacon('/log-error', payload);
} else {
fetch('/log-error', {
method: 'POST',
body: payload,
keepalive: true
}).catch(() => {});
}
}
基本上就这些。关键是把try-catch、onerror、unhandledrejection三者结合,形成完整的异常捕获链条,并持续收集分析错误数据,及时发现线上问题。
以上就是JavaScript错误处理_异常捕获与监控系统的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号