如何显示从服务器到客户端的第二个post请求的错误

ugmeyewa  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(181)

我有一个关于错误处理的问题。我有一个表单,提交后,向我的端点发出post请求。如果出现错误,catch块将变量状态设置为true,并显示一条消息。如果post成功,它将到达发送要保存的数据的第二个端点。如果此时有错误,catch块会在控制台中显示错误。我的问题是:我如何向我的前端显示这个错误?
在提交表格中:

try {
      await fetchForm(undefined, formData);
      setIsSuccessfullySubmitted(true);
      setTimeout(() => {
        setIsSuccessfullySubmitted(false);
      }, 3000);
    } catch (err) {
      setErrorForm(true);
      setTimeout(() => {
        setErrorForm(false);
      }, 5000);
    }

获取表单函数:(http是从axios.create方法创建的)

export const fetchForm = (url = '/myEndpoint', data: any): Promise<any> => {
  return http.post(url, data).then((res) => res.data);
};

在我的端点中:

try {
    if (something I need to check) {
      await postFormData(formData);
    } else {
      // something else but some post

      await postFormData(formData);
    }
  } catch (err) {
    console.log('something wrong****:', err.response.data);
  }

postformdata函数:

export async function postFormData(data: any): Promise<any> {
  return axios
    .post('http://the-second-endpoint', data)  
    .then((res) => res.data);
}

如果有错误,我会在控制台中得到('something error****:',err.response.data)消息以及来自服务器的响应({status:'fail'})。但是在我的前端,在提交之后,对于表单,一切都是好的。而是出现了一个错误。我如何才能告诉我的客户实际上存在错误并显示消息?谢谢

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题