【问题标题】:Angular HttpClient thrown error status codesAngular HttpClient 抛出错误状态码
【发布时间】:2021-11-12 07:25:06
【问题描述】:

在 Angular 文档中,声明将针对“不成功的 HTTP 状态”抛出 HttpErrorResponse。 (See here)

会抛出错误的不成功状态/不成功状态范围是什么? 是否存在即使 HTTP 状态为“不成功”,响应仍然有效的情况?

上下文:

在我的特殊情况下,我有一个身份验证服务。 RxJs 管道 switchMap 中有一个条件检查状态码是否在 200-399 范围内。这似乎是一个多余的检查。我想知道它是否可以删除。

this.http.get<UserDto>(ConstantUrlName.AUTHENTICATION_URL, {observe: 'response'}).pipe(switchMap((resp: HttpResponse<UserDto>) => {
    const user = resp &&
                resp.status >= 200 && resp.status < 400 &&
                resp.body;
    ....
}))

【问题讨论】:

  • 来自@jonrsharpe 的好链接,这也是我想说的。此检查是多余的,因为如果响应状态为&gt;= 400,它将在错误通道而不是事件通道上发出。

标签: angular rxjs angular-httpclient


【解决方案1】:

根据@jonrsharpe 的评论,我们可以在angular repository 中看到答案:

  // ok determines whether the response will be transmitted on the event or
   // error channel. Unsuccessful status codes (not 2xx) will always be errors,
   // but a successful status code can still result in an error if the user
   // asked for JSON data and the body cannot be parsed as such.
   let ok = status >= 200 && status < 300;

可能应该添加到 Angular 的文档中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多