HttpInterceptor重构错误消息

时间:2018-03-15 13:38:47

标签: angular http angular-http-interceptors

我有一个HttpInterceptor,我希望重构我的错误以删除括号。

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(public auth: AuthProvider, public app: App, private global: GlobalVariablesProvider) {}

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

    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {

      }
    }, (err: any) => {
      // modify err here?
    });
  }
}

我似乎无法直接修改err,而且我不确定如何在修改错误后传递错误。我想对err做出的修改是:

err.error.replace(/\[|]/, '')

1 个答案:

答案 0 :(得分:2)

在拦截器中,HTTP错误将被句柄(请求).catch(...)

捕获

你能做的是:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(public auth: AuthProvider, public app: App, private global: GlobalVariablesProvider) {}

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

        return next.handle(request)
            .do((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    // do what you want here if your have to
                }
            })
            .catch((err: any) => {
                if (err && err.error) {
                    err.error = err.error.replace(/\[|]/, '');
                }
                return Observable.throw(err);
            });
    }
}