admin管理员组

文章数量:1353303

The question is: what is best way to check status code when get http response? for example

fetch('/').then((response)=>{
    if (response.status >= 400) {
        //handle unsuccessful request ...
    }

    // or 
    if (response.status == 200) { 
        // status ok 
    }

});

However, the statements have magic number. e.g. 200 or 400. Is there best practice to avoid magic number?

The question is: what is best way to check status code when get http response? for example

fetch('https://stackoverflow./').then((response)=>{
    if (response.status >= 400) {
        //handle unsuccessful request ...
    }

    // or 
    if (response.status == 200) { 
        // status ok 
    }

});

However, the statements have magic number. e.g. 200 or 400. Is there best practice to avoid magic number?

Share Improve this question asked Apr 27, 2020 at 9:48 goodseeyougoodseeyou 531 gold badge1 silver badge3 bronze badges 4
  • 3 They are not magical numbers, they are HTTP response status codes – Luís Ramalho Commented Apr 27, 2020 at 9:51
  • You can define them as constants to make them more readable, but those constants will then hold “magic numbers”, which are the defined and standardized API interface though. – deceze Commented Apr 27, 2020 at 9:54
  • Thanks for your response. I know it's defined code. But when I develop backend service, I always use library to have http.StatusOK for 200 instead. Using number in if statement is not good for long term development. – goodseeyou Commented Apr 27, 2020 at 9:57
  • Does browser have built-in lib for status code definition? It's very mon usage. I think not good to maintain one for every developers. – goodseeyou Commented Apr 27, 2020 at 10:02
Add a ment  | 

1 Answer 1

Reset to default 5

The status code is the status property on the response object. Also, unless you're using JSON with your error responses (which some people do, of course), you need to check the status code (or the ok flag) before calling json:

fetch('https://jsonplaceholder.typicode./todos/1').then((response)=>{
    console.log(response.status); // Will show you the status
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    return response.json();
});

本文标签: javascriptBest way to check status code of http responseStack Overflow