这让我很紧张,我已经检查代码几个小时了,但找不到问题。在下面的代码中,我在正文中使用了无效对象以获得 400 错误(错误请求),因此在 catch block 中捕获它:
<button onClick={() => {
try {
axiosInstance.post('/cart', { field: "invalid field" });
} catch (err) {
console.log("here!!!");
console.error(err);
}
}}
/>
我可以在网络选项卡中看到请求失败,在控制台中我可以看到:
POST http://api.[REDACTED]/api/cart 400 (Bad Request)
index.js:1375 Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
最佳答案
Axios http请求是异步的,您需要使用Promises
或async/await
。尝试一下,您将看到错误响应:
<button onClick={async () => {
try {
const response = await axiosInstance.post('/cart', { field: "invalid field" });
} catch (err) {
console.log("here!!!");
console.error(err);
console.error(err.response);
}
}}
/>
关于javascript - Try-catch 对于 JS 中的 400 错误不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582828/