在应用全局http拦截器来处理错误之前,如何首先从组件返回错误?

时间:2018-05-03 01:50:59

标签: angular typescript error-handling angular-httpclient

目前,我正在使用http拦截器来全局处理所有错误。例如。如果http错误返回为404,则会显示一个快餐栏,其中显示" 404:找不到页面"通过http拦截器。这对于处理所有错误通常很有用,但有时,对于特定的服务调用,我知道问题是因为在商店中找不到商品而服务器返回404.而不是"找不到页面",我想要它返回"产品不在商店"仅用于那个电话。 404错误的其余部分可以一般地处理。

但是,我不知道如何做到这一点,因为Http拦截器在我的服务/组件中的错误处理之前首先出现。

此处是我的http拦截器:

@Injectable()
export class RequestInterceptor implements HttpInterceptor {

  constructor(
    public errorHandler: ErrorHandler,
  ) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).do((event: HttpEvent<any>) => {}, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        this.errorHandler.handleError(err);
      }
    });
  }
}

这是我的错误处理程序:

@Injectable()
export class ErrorHandler {

  constructor(
    public snackbar: MatSnackBar, private router: Router
  ) {}

  public handleError(err: any) {

    if (err.status === 400) {
        this.snackbar.open('400: There was a bad request', 'close');
    } else if (err.status === 401) {
        this.snackbar.open('401: Unauthorized', 'close');
    } else if (err.status === 403) {
        this.snackbar.open('403: Forbidden', 'close');
    } else if (err.status === 404) {
        this.snackbar.open('404: Page not found', 'close');
    } else if (err.status === 500) {
        this.router.navigate(['/error']);
    } else {
        this.snackbar.open(err.message, 'close');
    }
  }
}

例如这是我的服务电话,我希望首先出现错误:

getProductByNumber(storeId: number, productNum: number): Observable<any> {
   this.products = this.baseUrl + '/products/' + storeId + '/' + productNum;
   return this.http.get<IProduct>(this.products).catch(this.errorHandler);
  }

其中

errorHandler(error: HttpErrorResponse) {
    if (error.status === 404) {
      this.openSnackBar('Product is not found in store');
      return Observable.throw(error.message || 'Server Error');
    } else {
      return Observable.throw(error.message || 'Server Error');
    }
  }

0 个答案:

没有答案