Cause analysis of vue axios request successfully but entering catch

  • 2021-08-12 01:50:24
  • OfStack

Problem: axios returns a 200 status code (that is, the request is successful) but goes into catch

Reason:

1. When the axios request is completed, the code block of then, if there is error code information in the code block of then, then it will enter catch and throw an exception (note: the console will not report an error at this time, because the error was captured by catch)

2. axios is initiated asynchronously. If the page is refreshed after initiation, the current process will be lost, resulting in failure to receive it. For example, the form form will refresh after clicking the button to submit

Additional knowledge: What is the difference between axios written in catch and not using catch?

Writing on official website:


axios.post(url, data)
  .then(response => {
    console.log(response);
  })
  .catch(error => {
      console.log(error);
  })

Writing method of company project:


axios.post(url, data)
  .then(response => {
    console.log(response);
  }, error => {
    console.log(error);
  })

I haven't studied the writing of then and catch carefully before. In fact, this is not related to axios catch, but then about new Promise ()

Ruan 1feng is introduced in promise document.

1 In general, do not define the callback function of Reject state (that is, the second parameter of then) in the then method, and always use the catch method.


// bad
promise
 .then(function(data) {
  // success
 }, function(err) {
  // error
 });

// good
promise
 .then(function(data) { //cb
  // success
 })
 .catch(function(err) {
  // error
 });

In the above code, the second writing method is better than the first writing method, because the second writing method can catch the errors in the previous then method execution, and it is closer to the synchronous writing method (try/catch). Therefore, it is recommended that you always use the catch method instead of the second parameter of the then method.

The company's writing cannot be catch exception of the first parameter.

It may be easier to understand this way:


axios.post(url, data)
  .then(response => {
    // Processing logic 
  }, error => {
    console.log(' Interface error reporting ');
  })
  .catch(error=>{
    console.log(' Error in processing logic ');
  })

axios.post(url, data)
  .then(response => {
    // Processing logic 
  })
  .catch(error=>{
    console.log(' Error in interface or processing logic ');
  })

Related articles: