如何处理rxjs帖子引发的错误

时间:2018-08-14 19:46:12

标签: rxjs6

我正在通过后端服务发送一条post消息

return this.http.post(/*this.API_URL +*/this.NEW_QUESTION_URL,body,httpOptions)
      .map(response => { 
          return result; //map isn't required
        }

      })
      .catch(this.handleError); //error handler if Observable fails

handleError中,我抛出了一个错误

private handleError (error: HttpErrorResponse) {
console.error('WebToBackendInterfaceService::handleError', error);//I SEE THIS PRINT
        let result:ServerResponseAPI = {result:"error", "additional-info":error.message};
    return throwError(result);     
  }

我的问题-我想throwError返回一个Observable。我如何以及在哪里订阅此Observable,以便我可以处理错误?

我认为Observable返回的postthrowError返回的Observable不同。我已经订阅了post的{​​{1}}。

我还有一个自定义的拦截器。

return next.handle(cloned)
 .pipe(tap((ev: HttpEvent<any>) => { 
        console.log("got an event",ev);
        if (ev.type === HttpEventType.Response) {
          console.log('event of type Http response');
        }  else if (ev.type === HttpEventType.Sent) {
          console.log(" event of type httpsent");
        } else if(ev.type === HttpEventType.DownloadProgress){
          console.log("event of type download progress");
        } else if (ev.type === HttpEventType.UploadProgress) {
          console.log("event of type upload progress");
        } else if (ev.type === HttpEventType.User) {
          console.log("event of type user progress");
        }else if (ev.type === HttpEventType.ResponseHeader) {
          console.log("event of type response header")
        } else {
          console.log("don't know type",ev.type);
        }
      })
      ,catchError(errorResponse => {
          console.log("caught error from server",errorResponse) //I SEE THIS PRINT
          return observableThrowError(errorResponse);
      }));
    }

1 个答案:

答案 0 :(得分:0)

啊!我认为基本的Rxjs东西。在订阅一个可观察对象的同时,我可以提供数据,错误和完成的处理程序。我只提供了数据处理程序。

let subscription = this.dataService.addData(this.data)
    .subscribe((data) => {
            console.log("got data ", data)
        },
        (error) => {
            console.log("got error from the Observable: ", error)
        },
        () => {
            console.log("observable completed")
        });