Angular:http拦截器中的throwError,但无法捕获外部错误

时间:2019-01-22 08:43:16

标签: angular rxjs rxjs6

我在Angular 6上,我写了如下的自定义拦截器

intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const req = request.clone({
      headers: request.headers
        .set('Content-Type', 'application/json')
        .set('Accept', 'application/json')
    });

    console.log(req.urlWithParams);

    return next.handle(req).pipe(
      map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          // do stuff with response if you want
          let body = event.body;

          // here 10000 is our own error code
          if (body.code != 10000) {
            let err = {
              code: body['code'],
              message: body.message
            }

            return throwError(err);    // this error cannot be captured in subscriber
          } else {
            return body['data'];
          }
        } else {
          return event;
        }
      }),
      catchError(err => {
        if (err instanceof HttpErrorResponse) {
          console.error(err.message);

          if (err.status === 401) {
            this.authService.needSignIn();
          }
        }

        return throwError(JSON.parse(err.message));
      })
    );

map上方,我解析了响应正文,读取了自定义错误代码,并尝试抛出另一个错误。但是catchError和外部订户都无法捕获此错误。

就我而言,我想创建一个新错误,即使它是http 200并在订户中捕获该错误。 任何想法?谢谢

0 个答案:

没有答案