gpt4 book ai didi

javascript - 使用 fetch(),从非 HTTP OK 状态代码中读取响应主体并捕获异常

转载 作者:搜寻专家 更新时间:2023-10-30 21:33:25 34 4
gpt4 key购买 nike

我一直在阅读 fetch() 以及如何从服务器捕获和打印可读的错误消息。理想情况下,我想在下面的示例中抛出一个总是以 Catch 2 结尾的错误,并且 console.log(`OK: ${data}`); 是如果有错误则不会运行。我可以通过直接在 response.json(); 上运行 then 来缓解 console.log(`OK: ${data}`);但我想知道实现这一目标的正确方法。

https://stackoverflow.com/a/44576265/3850405

https://developers.google.com/web/updates/2015/03/introduction-to-fetch

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

C#:

[HttpGet, Route("api/specific/catalog/test")]
public async Task<IHttpActionResult> Test()
{
return InternalServerError(new Exception("My Exception"));
}

[HttpGet, Route("api/specific/catalog/test2")]
public async Task<IHttpActionResult> Test2()
{
return Ok("My OK Message");
}

typescript :

fetch('api/specific/catalog/test2')
.then(response => {
if (!response.ok) {
response.text().then(text => {
throw new Error(`Request rejected with status ${response.status} and message ${text}`);
})
.catch(error =>
console.log(`Catch 1: ${error}`)
);
}
else {
return response.json();
}
})
.then(data => {
console.log(`OK: ${data}`);
})
.catch(error =>
console.log(`Catch 2: ${error}`)
);

确定:

enter image description here

异常(exception):

enter image description here

我想我可以做这样的事情来捕获所有错误,但它看起来很奇怪:

fetch('api/specific/catalog/test')
.then(response => {
if (!response.ok) {
response.text().then(text => {
throw new Error(`Request rejected with status ${response.status} and message ${text}`);
})
.catch(error =>
console.log(`Catch: ${error}`)
);
}
else {
return response.json().then(data => {
console.log(`OK: ${data}`);
})
.catch(error =>
console.log(`Catch 2: ${error}`)
);
}
})
.catch(error =>
console.log(`Catch 3: ${error}`)
);

最佳答案

问题是你吞下了里面的错误,你也不需要多次捕获你只需要最后一个这样:

fetch('api/specific/catalog/test')
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error(`Request rejected with status ${response.status} and message ${text}`);
})
}
else {
return response.json()
}
})
.then(data => {
console.log(`OK: ${data}`);
})
.catch(error =>
console.log(`Catch 3: ${error}`)
);

关于javascript - 使用 fetch(),从非 HTTP OK 状态代码中读取响应主体并捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55833486/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com