没有写 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 errorHandler
- Vue.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;
- }
- }
(编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|