How to catch NetworkError in JavaScript?

百般思念 提交于 2019-12-05 11:26:48

问题


In Chrome's JavaScript console, if I run this:

var that = new XMLHttpRequest();
that.open('GET', 'http://this_is_a_bad_url.com', false);
that.send();

I get an intentionally expected error:

NetworkError: A network error occurred.

I want to catch this, so I use:

var that = new XMLHttpRequest();
that.open('GET', 'http://this_is_a_bad_url.com', false);
try {
  that.send();
} catch(exception) {
  if(exception instanceof NetworkError) {
    console.log('There was a network error.');
  }
}

However, I get an error about NetworkError not being defined:

ReferenceError: NetworkError is not defined

How can I catch NetworkError?


回答1:


I think what you meant was:

if(exception.name == 'NetworkError'){
   console.log('There was a network error.');
}

I don't believe the Error is an instance of NetworkError, but thrown in this manner:

throw {
   name: 'NetworkError',
   message: 'A network error occurred.'
   // etc...
}



回答2:


I found this answer while looking for a way to examine a Network Error I got while using Axios, so if You are not using Axios, this answer is probably not for You.

The error object I receive through Axios has config, request and response attributes, and both the request and response have the status attribute. response object's attribute is displayed in the image below:

My axios configuration looks like this:

this.client = axios.create(options);
this.client.interceptors.response.use(this.handleSuccessResponse, this.handleErrorResponse);
this.unauthorizedCallback = () => {};

and the handleErrorResponse method is:

handleErrorResponse(error) {
  // use the information from the error object here
}



回答3:


Look into the onreadystatechange event. You can get the status of the response.




回答4:


exception.name returns 'Error' even on network errors a better way can be checking if error has url config like this :

if(exception.config && exception.config.url){
  // network error
} else {
  // other errors
}


来源:https://stackoverflow.com/questions/20231075/how-to-catch-networkerror-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!