How to appropriately handle error responses Angular 4.0.0

走远了吗. 提交于 2019-12-11 07:06:37

问题


I've got a problem with handling errors in Angular 4. Please advice me the proper approach. When server respond with error I'd like to redirect it to cache block and there I'd like to have a specific behaviour when status is 403. When I check the status in the first map() and throw an error from there - catch block is executed, but error is passing as a string with stack trace. It makes unpossible to recognize status in catch block again. How to do it right way?

getLoggedInUser(): Observable<User> {
  return this.http.get(this.baseApiUrl + `api/user/me`)
    .map((res: Response) => {
      if(res.status < 200 || res.status >= 300) {
        console.log(res.status);
        throw new Error();
      } 
      else {
        return res.json();
      }
    })
    .map((user) => {
      let deserializedUser = new User().deserialize(user)
      this._loggedInUser = deserializedUser;
      return deserializedUser;
    })
    .catch((errorStatus: any) => { 
      console.log(errorStatus.status);
      if (errorStatus === "403") {
        console.log(errorStatus);
        this.isRequestForbidden = true;
      }
      return Observable.throw(errorStatus || 'Server error') 
    });
}

来源:https://stackoverflow.com/questions/45879364/how-to-appropriately-handle-error-responses-angular-4-0-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!