| 没有写 catch的Promise中抛出的错误无法被onerror或try-catch捕获到,所以我们务必要在Promise中不要忘记写catch处理抛出的异常。 解决方案: 为了防止有漏掉的 Promise异常,建议在全局增加一个对unhandledrejection的监听,用来全局监听Uncaught Promise Error。使用方式: window.addEventListener("unhandledrejection", function(e){ console.log(e); }); 
 我们继续来尝试一下: window.addEventListener("unhandledrejection", function(e){ e.preventDefault() console.log('捕获到异常:', e); return true; }); Promise.reject('promise error'); 
 可以看到如下输出: 
 那如果对 Promise不进行catch呢? window.addEventListener("unhandledrejection", function(e){ e.preventDefault() console.log('捕获到异常:', e); return true; }); new Promise((resolve, reject) => { reject('jartto: promise error'); }); 
 嗯,事实证明,也是会被正常捕获到的。 所以,正如我们上面所说,为了防止有漏掉的 Promise异常,建议在全局增加一个对unhandledrejection的监听,用来全局监听Uncaught Promise Error。 补充一点:如果去掉控制台的异常显示,需要加上: event.preventDefault(); 
 七、VUE errorHandlerVue.config.errorHandler = (err, vm, info) => { console.error('通过vue errorHandler捕获的错误'); console.error(err); console.error(vm); console.error(info); } 
 八、React 异常捕获React 16提供了一个内置函数componentDidCatch,使用它可以非常简单的获取到react下的错误信息
 componentDidCatch(error, info) { console.log(error, info); } 
 除此之外,我们可以了解一下:error boundary
 UI的某部分引起的JS错误不应该破坏整个程序,为了帮React的使用者解决这个问题,React 16介绍了一种关于错误边界(error boundary)的新观念。 需要注意的是: error boundaries 并不会捕捉下面这些错误。 1.事件处理器2.异步代码
 3.服务端的渲染代码
 4.在
 error boundaries区域内的错误 我们来举一个小例子,在下面这个 componentDIdCatch(error,info)里的类会变成一个error boundary: class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; }   componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service logErrorToMyService(error, info); }   render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } } 
 (编辑:宣城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |