【问题标题】:Angular http handling json response in case of http error发生http错误时的角度http处理json响应
【发布时间】:2020-11-10 22:48:37
【问题描述】:

我无法解决这个问题,在网上我找不到任何东西,我这样打电话:

return this.http.post(url, body, { headers: ConnectFunctions.getHeader() }).pipe(
  map(result => {
    return result;
  }),
  catchError(ConnectFunctions.handleError(url, []))
);
}

这是我从服务器得到的响应

{"status":500,"timestamp":"21-07-2020 03:51:17","message":"my custom message","details":"some details"}

我想获取变量消息(“我的自定义消息”),但我不能。

public static handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
        console.log("Error use: " + `${operation} failed: ${error.message}`);
        console.log("Error statusText: " + error.statusText);
        return of(error as T);
    };
}

我该怎么做?

感谢您的帮助。

【问题讨论】:

  • 您的地图功能没有多大意义。但忽略这一点,这是我从服务器得到的响应是实际的 HTTP 500 状态代码还是只是在正文中说? I'm not able [to] 是什么意思?你订阅过这个 observable 吗?
  • 这是我从网络标签下的 Chrome 开发者工具中看到的从服务器接收到的原始响应数据。
  • 那没有回答我的任何问题。请告诉我们minimal reproducible example

标签: angular typescript rxjs httpclient


【解决方案1】:

有一些方法可以捕获错误,但你可以总结一下:

return this.http.post(url, body, { headers: ConnectFunctions.getHeader() })
      .catch((err: HttpErrorResponse) => {
    // simple logging, but you can do a lot more,
    console.error(err.error.message);
  });

详细了解 HttpErrorResponse:https://angular.io/api/common/http/HttpErrorResponse

【讨论】:

  • 这是正确的答案。谢谢。如果我无法更好地解释自己,我很抱歉 Liam,但这个答案挽救了我的一天。
猜你喜欢
  • 1970-01-01
  • 2019-10-12
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
  • 2020-07-24
相关资源
最近更新 更多