React.js:尽管 http 响应 400,但仍收到错误消息

por*_*ume 5 post reactjs

我有一个场景,如果我在数据库中保存重复记录,模式应该显示确切的错误消息

使用 axios 的 POST 请求:

    saveBankMaintenance(optionsBrstn){
        return axios.post(`${API_URL_SAVE_BANK_MAINTENANCE}`, 
            [optionsBrstn]
    )
Run Code Online (Sandbox Code Playgroud)

我使用以下方式调用此 POST 请求:

const saveBrstn = useCallback(() => {
    ClientMaintenanceService.saveBankMaintenance(optionsBrstn)
    .then((response) => {
      if(response.data.success === "Success"){
        setShowBrstnSaveSuccessModal(true);
        setShowBrstnSaveFailedModal(false);
      }
    }).catch((err) => {
        setShowBrstnSaveSuccessModal(false);
        setShowBrstnSaveFailedModal(true);
    })
  });
Run Code Online (Sandbox Code Playgroud)

保存成功就OK了

但是,当它失败时,它会直接进入catch块,我无法在状态上设置错误消息

有没有办法让我获得 json 响应(包含错误消息)以及 http 状态响应 400?

TIA

Soh*_*raf 13

error您可以在属性中的对象中获取响应数据response

尝试这个。

const saveBrstn = useCallback(() => {
    ClientMaintenanceService.saveBankMaintenance(optionsBrstn)
        .then((response) => {
            if (response.data.success === "Success") {
                setShowBrstnSaveSuccessModal(true);
                setShowBrstnSaveFailedModal(false);
            }
        }).catch((err) => {
            console.log(err.response.data); // you can get the response like this
            console.log(err.response.status); // status code of the request

        })
});
Run Code Online (Sandbox Code Playgroud)