简体   繁体   中英

Reactjs Axios not going to catch

I got the following function but when it encountered an error it didn't event go to catch it just went straight to then. Note that this was working I was just trying to force the catch

const AddMainItem = HPSMainObject => {
  let data = JSON.stringify(HPSMainObject);

  const request = axios({
    method: "POST",
    url: getMainUrl(
      "web/lists/GetByTitle('" +
        MAINITEMGENERALINFO.mainItemRelatedObject.mainList.title +
        "')/Items"
    ),
    data: data,
    headers: INTERNALCONFIG.PostHeader
  });

  return request.then(result => result.data.d).catch(error => error);
};

I called it using this, can you advise whats the best practice?

handleSubmit = () => {
    let self = this;
    AddMainItem(self.state.HPSMainObject)
      .then(function(AddMainItemResult) {
        console.log("its working");
      })
      .catch(function(errorMessage) {
        console.log("Error AddMainItem: ", errorMessage);
      });
}

This line:

.catch(error => error)

...converts rejected Promises to Promises that resolve to the error. It's the equivalent of doing this in synchronous code:

try {
  doSomething();
} catch (error) {
  return error; // The function is no-longer throwing
}

It seems what you're wanting to do is:

.catch(error => { throw error; })

...but that's redundant. Just omit the catch, and the caller's catch will kick in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM