首页 > 解决方案 > 发生http错误时的角度http处理json响应

问题描述

我无法解决这个问题并且在网上我找不到任何东西,我做了一个这样的邮寄电话:

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);
    };
}

我该怎么做?

谢谢你的帮助。

标签: angulartypescriptrxjshttpclient

解决方案


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

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


推荐阅读