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