【发布时间】:2019-09-13 22:53:06
【问题描述】:
我一直在阅读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");
}
打字稿:
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}`)
);
【问题讨论】:
-
甚至没有到达服务器与服务器回答错误代码和消息有很大不同。您的第一个 catch2 只会捕获格式错误的 URL 或 CORS 内容等。纯粹从 JS 的角度来看,您可以重构代码,以便单个函数处理两个异常。只需创建一个函数并将其设置为
catch处理程序即可。
标签: javascript c# typescript fetch