我一直在阅读fetch()
,以及如何捕获和打印来自服务器的可读错误消息。理想情况下,我想在下面的示例中抛出一个始终以Catch 2
结尾的错误,并且如果发生错误,则console.log(`OK: ${data}`);
不会运行。我可以通过直接在console.log(`OK: ${data}`);
上运行then
来缓解response.json();
的问题,但是我想知道实现此目标的正确方法。
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");
}
打字稿:
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}`)
);
确定:
例外:
我想我可以做这样的事情来捕捉所有错误,但看起来很奇怪:
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}`)
);
答案 0 :(得分:1)
问题在于您随后吞下了错误,也不需要多个捕获,而最终只需要这样一个捕获即可:
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}`)
);