如何处理fetch API中的HTTP代码4xx响应
我想知道当使用Ajax功能时,如何从后端处理400。我们可以在Promise Resolve功能中进行IF IF语句,并检查RES状态是否为400。不同的方法正在为获取包装服务,而当我们从服务器获得400时,我们会抛出异常。如何解决这个问题?
I was wondering how we should handle 400 from backend when we use ajax function. We can make if statement in promise resolve function and check if res status is 400. Different approach is making wrapper service for fetch, and when we got 400 from server we throw exception. How to deal with that problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议一个检查
Response.ok
的包装器,如果响应代码为2xx,则将是正确的。请注意此语句来自 :
这是这样的包装器:
I'd suggest a wrapper that checks
response.ok
which will be true if the response code is 2xx.Note this statement from the MDN page on
fetch()
:Here is a wrapper like this:
这样,我们可以相应地处理所有类型的状态。
Inspiration
This way we can handle all types of status accordingly.
inspiration
将其纳入您的HTTP抽象可能是一个好主意。也许有了某种
选项
参数:围绕
提取
的包装器通常是一个好主意,fetch
是一个相对较低的级别函数。就像直接在各处创建新的XHR对象并不是一个好主意一样,我相信在应用程序的各个部分中直接调用fetch()
并不是一个好主意。在某些方面,它类似于全局变量。Incorporating it into your HTTP abstraction is probably a good idea. Perhaps with some sort of
options
argument:A wrapper around
fetch
is generally a good idea,fetch
is a relatively low level function. Just as it isn't a good idea to directly create new XHR objects everywhere, I believe it isn't a good idea to directly callfetch()
in various parts of your application. It's akin to a global variable, in some ways.我发现的最佳方法是将其包裹在一个新的承诺中,如果
Response.ok
是错误的,请在错误上下文中拒绝承诺。( https://github.com/github.com/github/fetch/sissues/203 )
The best approach I've found for this is to wrap it in a new Promise, and if
response.ok
is false, reject the Promise with the error context.(Top comment on https://github.com/github/fetch/issues/203)