英文:
Try-catch is not working for 400 errors in JS
问题
这让我感到烦恼,我已经检查了几个小时的代码,但找不到问题。在下面的代码中,我在请求体中使用了一个无效的对象,以便获得400错误(Bad Request),然后在catch块中捕获它:
<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)
英文:
This is getting on my nerves, I've been checking the code for a few hours and can't spot the problem. in the below code, I'm using an invalid object in the body in order to get 400 error (Bad Request) and therefore catch it in the catch block:
<button onClick={() => {
try {
axiosInstance.post('/cart', { field: "invalid field" });
} catch (err) {
console.log("here!!!");
console.error(err);
}
}}
/>
I can see the request fail in network tab, in console I can see:
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)
答案1
得分: 6
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);
}
}}
/>
英文:
Axios http requests are async, you need to use Promises
or async/await
. Try this and you will see the error response:
<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);
}
}}
/>
答案2
得分: 1
Https请求是异步的,你需要将处理程序标记为异步,并等待调用的结果。
<button
onClick={async () => {
try {
return await axiosInstance.post('/cart', { field: "invalid field" });
} catch (err) {
console.log(err);
}
}}
>
异步点击我
</button>
以下的沙盒展示了两边的情况。
英文:
Https requests are asynchronous, you need to make the handler async and await the result of the call.
<button
onClick={async () => {
try {
return await axiosInstance.post('/cart', { field: "invalid field" });;
} catch (err) {
console.log(err);
}
}}
>
async press me
</button>
The following sandbox shows each side-by-side.
答案3
得分: 0
如果此错误响应未在控制台中显示“here!!”,则错误肯定发生在此代码部分之前,可能在axios声明或axios请求表单中。
尝试将axios选项配置在一个JSON对象内,如下所示:
axios({
method: "post",
url: "..."
});
英文:
If this error response don't show "here!!" In console, certainly the error is caused before this code section, probably in axios declaration or axios request form.
Try configure axios options inside a json object like:
axios({
method: "post",
url: "..."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论