繁体   English   中英

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

[英]Use fetch(), read response body from non HTTP OK status codes and catch the exception

我一直在阅读fetch()以及如何从服务器捕获和打印可读的错误消息。 理想情况下,我想抛出一个错误,该错误总是在下面的示例中以Catch 2结束,并且console.log(`OK: ${data}`); 如果出现错误,则不会运行。 我可以减轻console.log(`OK: ${data}`); then直接在response.json();上运行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}`)
    );

问题是你把错误吞进去了,你也不需要多次捕获,最后只需要一个,就像这样:

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}`)
    );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM