How to catch NetworkError in JavaScript?

前端 未结 4 630
失恋的感觉
失恋的感觉 2021-02-07 01:30

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();


        
相关标签:
4条回答
  • 2021-02-07 01:47

    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...
    }
    
    0 讨论(0)
  • 2021-02-07 01:48

    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
    }
    
    0 讨论(0)
  • 2021-02-07 01:51

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

    0 讨论(0)
  • 2021-02-07 01:57

    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
    }
    

    EDIT: As suggested by @Erdős-Bacon:

    If You are using axios and nginx, this might be the comment for You. I had issues with error.response being undefined, turned out it was because of CORS issue. Had to setup my nginx config to keyword always add appropriate headers to solve CORS, otherwise headers get stripped on error responses, so CORS issues crop up. See this answer for more info.

    0 讨论(0)
提交回复
热议问题