最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use fetch(), read response body from non HTTP OK status codes and catch the exception - Stack Overflow

programmeradmin0浏览0评论

I have been reading up on fetch() and how to catch and print a readable error message from the server. Ideally I would like to throw an error that always ends up in Catch 2 in my example below and that console.log(`OK: ${data}`); is not ran if there is an error. I can mitigate console.log(`OK: ${data}`); by running then directly on response.json(); instead but I would like to know the proper way of achieving this.

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

Typescript:

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

OK:

Exception:

I guess I could do something like this to catch all errors but it seems weird:

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

I have been reading up on fetch() and how to catch and print a readable error message from the server. Ideally I would like to throw an error that always ends up in Catch 2 in my example below and that console.log(`OK: ${data}`); is not ran if there is an error. I can mitigate console.log(`OK: ${data}`); by running then directly on response.json(); instead but I would like to know the proper way of achieving this.

https://stackoverflow./a/44576265/3850405

https://developers.google./web/updates/2015/03/introduction-to-fetch

https://developer.mozilla/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");
}

Typescript:

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

OK:

Exception:

I guess I could do something like this to catch all errors but it seems weird:

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}`)
    );
Share Improve this question asked Apr 24, 2019 at 15:18 OgglasOgglas 70.4k42 gold badges377 silver badges473 bronze badges 1
  • Not even reaching a server is very different from the server answering with an error code and message. Your first catch2 will only catch malformed URLs or CORS stuff and the like. Purely from a JS perspective you can refactor the code so a single functions handles both exceptions. Just create a function and set it as catch handler for both. – user5734311 Commented Apr 24, 2019 at 15:25
Add a ment  | 

1 Answer 1

Reset to default 8

The problem is that you swallow the error inside then, also you don't need multiple catches you only need one at the end like this:

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论