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

I have been reading up on fetch() and how to catch and print a readable error message from the server.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742328444a4423224.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信