原文链接: react 异常捕获
上一篇: ts 实现fib
参考
https://zhuanlan.zhihu.com/p/259571403
这些人的脑洞可真大...
用户的执行函数
const f = () => JSON.parse();
const test = () => {
console.log("test 1");
f();
console.log("test 2");
};
使用try-catch

必须开启两个才能在异常位置停下来

const wrapProd = (fn) => {
try {
fn();
} catch (e) {
console.log("try", e);
}
};
console.log("wrap1");
wrapProd(test);
console.log("wrap2");
使用window的error事件
可以停到代码异常位置

但是代码却无法继续向下执行

const wrapDev = (fn) => {
const handler = (e) => {
console.log("handler", e);
};
window.addEventListener("error", handler);
fn();
window.removeEventListener("error", handler);
};
使用node结点派发函数的方式
可以停留也能继续执行


function wrapDev2(func) {
function handleWindowError(e) {
// 收集错误交给Error Boundary处理
console.log("handle2", e);
}
function callCallback() {
fakeNode.removeEventListener(evtType, callCallback, false);
func();
}
const event = document.createEvent("Event");
const fakeNode = document.createElement("fake");
const evtType = "fake-event";
window.addEventListener("error", handleWindowError);
fakeNode.addEventListener(evtType, callCallback, false);
event.initEvent(evtType, false, false);
fakeNode.dispatchEvent(event);
window.removeEventListener("error", handleWindowError);
}
304

被折叠的 条评论
为什么被折叠?



