如何提取服务器发送的错误消息



服务器:

// code
return res.status(400).json("Email already exist");

客户端:


export const register = async (credentials, dispatch) => {
try {
const res = await axios.post("/auth/register", credentials);
dispatch(success(res.data));
document.cookie = res.data.access_token;
} catch (err) {
dispatch(register_error());
}
dispatch(end());
};

当该消息被发送时,事情进入了catch块,我不知道如何从err对象中精确获取Email already exist消息。

这是catch块中的err.response.data

Axios 中的错误处理

根据Axios文档,您可以访问以下错误

axios.get('/user/12345').catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config); 
});

使用validateStatusconfig选项,您可以定义应该引发错误的HTTP代码。

axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Resolve only if the status code is less than 500
}
});

使用toJSON可以获得一个包含有关HTTP错误的更多信息的对象。

axios.get('/user/12345').catch(function (error) {
console.log(error.toJSON());
});

相关内容

最新更新