RxJs-没有订户处理错误时的默认错误处理程序

时间:2018-08-19 03:07:25

标签: javascript angular typescript rxjs

我正在Angular 6应用程序中为RxJ寻找可覆盖的默认错误处理程序。寻找以下行为

my-service.ts

getArticle(id: string) {
  return this.http.get<Article>(`/api/articles/${id}`).pipe(
    defaultHandler(err => {
      console.log('Default error handler', err);
      // TODO Show dialog saying: err.data.msgFromServer || 'Unknown error'
    })
  );
}

情况1:没有订阅者处理错误

myService.getArticle('1234').pipe(map(...), ...otherOperators)
  .subscribe(this.onNext); // Default error handler HttpErrorResponse {...}

情况2:至少一个订户处理错误

myService.getArticle('1234').pipe(map(...), ...otherOperators)
  .subscribe(this.onNext, err => console.log('Hi from subscriber'));
// Hi from subscriber

1 个答案:

答案 0 :(得分:0)

handleError()是HTTP拦截器的默认错误处理程序的示例。 它会在此处处理一般的http错误,并将其参数('Error Occured')发送到您预订的postCall()所在的任何地方。

export class Http extends HttpClient {

   constructor(httpHandler: HttpHandler) {
      super(httpHandler);
   }

   postCall(url: string, body, options?): Observable<any> {
      return super.post(url, body, options)
          .pipe(
             tap(response => { console.log(response) }),
             catchError(this.handleError('Error Occured')));
             // 'Error Occured' or anything here goes to anywhere you subscribe postCall() as response
   }

  private handleError<T>(result?: T) {
     return (error: any): Observable<T> => {
        console.error('Status: ', error.status); // Example output 'Status: 401'
        return of(result as T);
     };
  }
}