【问题标题】:Use fetch(), read response body from non HTTP OK status codes and catch the exception使用 fetch(),从非 HTTP OK 状态码中读取响应体并捕获异常
【发布时间】: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


【解决方案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}`)
    );

【讨论】:

  • 当然,完全错过了return response.text()。谢谢!
猜你喜欢
  • 2017-04-22
  • 2017-12-14
  • 2019-01-03
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 2021-03-15
  • 1970-01-01
相关资源
最近更新 更多