axios不会分别返回响应和错误

时间:2019-09-26 20:48:54

标签: javascript reactjs promise axios

我有一个React组件。在该组件内部,我有一个函数onFormSubmit,它从另一个组件调用函数。另一个功能是通过axios发出POST请求。 如果POST请求为true,我想返回对第一个函数的响应,否则返回错误。现在发生的是,即使在axios POST请求中存在错误,我的“ SUCCESS RESPONSE” console.log始终会被触发。如果有错误,则仅应触发“ ERROR RESPONSE” console.log。

从第一个组件开始

public SeriesCollection SeriesCollection { get; set; } = new SeriesCollection
{
  new ColumnSeries
  {
    Title = "Series A",
    Values = new ChartValues<double> { 10, 20, 30, 20, 10},
    Fill = Brushes.CornflowerBlue
  },
  new ColumnSeries
  {
    Title = "Series B",
    Values = new ChartValues<double> { 100, 200, 300, 200, 100 },
    Fill = Brushes.DarkOrange
  }
};

来自第二部分

 onFormSubmit = () => {
    postJobDescriptionQuickApply(this.state, this.props.jobDescription.id)
      .then((response) => {
        console.log('SUCCESS RESPONSE', response)
      })
      .catch((error) => {
        console.log('ERROR RESPONSE', error)
      })
  }

3 个答案:

答案 0 :(得分:5)

调用return表示成功,并且不会触发调用方法中的.catch函数。不要返回error.response.data.developerMessage,而要使用throw。这将导致它被抛出,然后被调用函数中的.catch方法捕获。

但是,根据情况,通常不建议捕获并重新抛出异常,因为这样会丢失堆栈跟踪等信息。最好不要在lower方法中捕获错误,而仅依靠调用方法来处理错误。错误。

答案 1 :(得分:0)

不要在第二个组件上使用catch and catch。

要使用然后使用第一个组件,您需要返回axios,如下所示:

export const postJobDescriptionQuickApply = (easyApplyData, jobId, url) => axios
  .post(url, {
    applicant: {
      email: easyApplyData.email,
      ...
    },
    job: {
      jobId,
    },
  });

// or using apiUrl

export const postJobDescriptionQuickApply = (easyApplyData, jobId) => apiUrl('easyApply', 'easyApply')
 .then(url => axios.post(url, {
    applicant: {
      email: easyApplyData.email,
      fullName: `${easyApplyData.firstName} ${easyApplyData.lastName}`,
      phoneNumber: easyApplyData.phoneNumber,
      resume: easyApplyData.resume,
      source: easyApplyData.source,
    },
    job: {
      jobId,
    },
  });

此外,不要忘记在第一个组件中验证响应状态,如下所示:

onFormSubmit = () => {
    postJobDescriptionQuickApply(this.state, this.props.jobDescription.id)
      .then((response) => {
          if (response.status === 200) {
             console.log('SUCCESS RESPONSE', response);
          }

      })
      .catch((error) => {
        console.log('ERROR RESPONSE', error)
      })
  }

我希望能为您提供帮助

答案 2 :(得分:0)

 .catch((error) => {
   // handle error
   console.log('ERROR JOB DESCRIPTION', error.response.data.developerMessage)
   return error.response.data.developerMessage
 })

throw error

代替return语句
相关问题