2017-07-24 110 views
1

得到正确的错误我有一个doFetch函数来处理我所有的API调用:无法从Axios公司

const doFetch = function(params){ 
    ... 
    // Make request using Axios. Axios is promise based. 
    return axios({ 
     method: method, 
     url: baseUrl + url, 
     data: queryParams, 
     timeout: timeout, 
     headers: { 
      'Content-Type': contentType, 
      'Authorization': `bearer ${Auth.getToken()}` // set the authorization HTTP header 
     }, 
     responseType: responseType 
    }).then((response) => { 
     if(typeof params.callback === "function"){ 
      params.callback(response); 
     } 
     else { 
      return response; 
     } 
    }).catch((err) => { 
     if(typeof params.error === "function") { 
      if (err.response) { 
       params.error(err.response.data); 
      } 
     } 
     else{ 
      if (err.response) { 
       return err.response.data; 
      } 
      else{ 
       return err; 
      } 
     } 
    }); 
}; 

一个这样的API调用返回,像这样一个自定义错误(Express服务器):

return res.status(400).json("There was an error on the server."); 

调用doFetch功能是saveUser

saveUser(userObj).then((response) => {     
    console.log("No Error"); 
}).catch((error) => { 
    console.log("Error:", error); 
}); 

的问题是,我seein g No Error在终端,当我只应该期待的错误信息显示。有任何想法吗?

回答

1

我喜欢准确地回复承诺,以确保它能够/返回我想要的。

我不喜欢依赖第三方的“承诺”。


因此,我建议你手动包装它承诺的内部和解决/拒绝响应/错误:

const doFetch = params => { 
    ... 
    // Make request using Axios. Axios is promise based. 
    return new Promise((resolve, reject) => { 
     axios({ 
     method: method, 
     url: baseUrl + url, 
     data: queryParams, 
     timeout: timeout, 
     headers: { 
      'Content-Type': contentType, 
      'Authorization': `Bearer ${Auth.getToken()}` // set the authorization HTTP header 
     }, 
     responseType: responseType 
     }) 
     .then((response) => { 
     console.info('doFetch:', response); // for debug purposes 

     if(typeof params.callback === "function"){ 
      params.callback(response); 
     } 
     resolve(response); 
     }) 
     .catch((err) => { 
     console.error('doFetch:', err); // for debug purposes 

     const error = (err.response) ? err.response.data : err; 

     if(typeof params.error === "function") { 
      params.error(error); 
     } 
     reject(error); 
     }); 
    }; 
}; 
+1

大加赞赏。 – JoeTidee