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
1 Answer
Reset to default 5The 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
版权声明:本文标题:javascript - Best way to check status code of http response? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743926916a2563131.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论