我有一些在提交表单时执行的代码。 它发布到 API 路由。
handleSubmit = async () => {
try {
const response = await fetch(`${API_URL}/project`, {
method: "post",
body: JSON.stringify({
name: this.state.name,
description: this.state.description
}),
headers: { "Content-Type": "application/json" }
});
return response ? response.json() : response;
} catch (error) {
console.log(error)
}
};
问题是,在测试时,我将 API 路由更改为故意无效的路由,以导致错误。然而,catch 代码没有被击中。 我是否设置了错误的 try-catch?
最佳答案
您面临的问题是收到 404 并不异常(exception)。为了解决这个问题,您应该添加一些代码来检查响应的状态代码,并从那里确定应该做什么。例如,您将收到响应并使用以下内容:
if(response.status == 404)
//Code for not receiving the content you expect
问题是,您可能会收到很多潜在的响应,但这些响应并不是您想要的,因此我实际上建议将特定响应范围列入白名单,而不是寻找有问题的响应范围。例如
if(response.status >= 200 && response.status <= 299)
//Code to run when you receieve a good response
这是一个示例,由您决定您希望处理哪些响应。
关于javascript - 即使发生错误, try catch 也不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55718465/