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

Ogg*_*las 7 javascript c# fetch typescript

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

/sf/answers/3120338581/

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");
}
Run Code Online (Sandbox Code Playgroud)

打字稿:

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}`)
    );
Run Code Online (Sandbox Code Playgroud)

好的:

在此处输入图片说明

例外:

在此处输入图片说明

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

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}`)
    );
Run Code Online (Sandbox Code Playgroud)

jcu*_*bic 8

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

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}`)
    );
Run Code Online (Sandbox Code Playgroud)