简体   繁体   English

使用 Angular 7 处理 HTTPErrorResponse 的最佳方法

[英]Best way to handle HTTPErrorResponse with Angular 7

So the backend Server returns different status code and HttpErrorResponse when there are erroneous requests from the front end;所以后端Server在前端有错误请求时返回不同的状态码和HttpErrorResponse; I have realised the best way to manage this is using interceptors in an Ionic 4/Angular 7 setup.我已经意识到管理这个问题的最佳方法是在 Ionic 4/Angular 7 设置中使用拦截器。

I have tried interceptors a couple of times and I am stuck with different issues.我已经尝试过几次拦截器,但遇到了不同的问题。 I am now following the steps in this link我现在正在按照此链接中的步骤进行操作

My services are defined like this :我的服务定义如下:

     saveLocationNew(request: AddLocationRequest, entityId:string, userId:string): Observable<AddLocationResponse> {

          return this.httpClient.post<AddLocationResponse>(this.addLocationUrl, request ,  {headers:Constants.getHeaders(userId,entityId)})
       }

With the interceptors it is now :使用拦截器现在是:

    saveLocationNew(request: AddLocationRequest, entityId:string, userId:string): Observable<AddLocationResponse> {

      return this.httpClient.post<AddLocationResponse>(this.addLocationUrl, request ,  {headers:Constants.getHeaders(userId,entityId)})
      .pipe(
    tap(_ => console.log('creating a new location')),
    catchError(this.handleError('new Location',[]))
  );  
}

The issue being my existing service returns a response of type of AddLocationResponse;问题是我现有的服务返回 AddLocationResponse 类型的响应; but in case of error how do I define the type of the return object and ionic serve also throws this error :但是如果出现错误,我该如何定义返回对象的类型,而 ionic serve 也会抛出这个错误:

    ERROR in src/app/services/location.service.ts(42,11): error TS2322: Type 'Observable<any[] | AddLocationResponse>' is not assignable to type 'Observable<AddLocationResponse>'.
[ng]   Type 'any[] | AddLocationResponse' is not assignable to type 'AddLocationResponse'.
[ng]     Type 'any[]' is not assignable to type 'AddLocationResponse'.
[ng]       Property 'name' is missing in type 'any[]'.
[ng] src/app/services/location.service.ts(74,49): error TS2339: Property 'message' does not exist on type 'T'.

Any idea what would be the best way to implement interceptors so that the component(*.page.ts files) won't need any change .知道什么是实现拦截器的最佳方法,这样组件(*.page.ts 文件)就不需要任何更改。

My interceptor looks like this :我的拦截器看起来像这样:

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

  const token = localStorage.getItem('token');

  if (token) {
    request = request.clone({
      setHeaders: {
        'Authorization': token
      }
    });
  }

  if (!request.headers.has('Content-Type')) {
    request = request.clone({
      setHeaders: {
        'content-type': 'application/json'
      }
    });
  }

  request = request.clone({
    headers: request.headers.set('Accept', 'application/json')
  });

  return next.handle(request).pipe(
    map((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        console.log('event--->>>', event);
      }
      return event;
    }),
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        if (error.error.success === false) {
          this.presentToast('Login failed');
        } else {
            console.log(' route this to right place');
        //   this.router.navigate(['auth/login']);
        }
      }
          if (error.status === 500) {
        if (error.error.success === false) {
          this.presentToast('Something went wrong, Please contact Administrator');
        } else {
            console.log(' route this to right place');
        //   this.router.navigate(['auth/login']);
        }
      }
      //431

       if (error.status === 431) {
        if (error.error.success === false) {
          this.presentToast('Something went wrong with the HttpRequest, Please contact Administrator');
        } else {
            console.log(' route this to right place');
        //   this.router.navigate(['auth/login']);
        }
      }

      // add all the other error codes here 
      return throwError(error);
    }));
}

I am not sure what else needs to be added/modified so that the HttpErrorResponse will be intercepted.我不确定还需要添加/修改什么,以便拦截 HttpErrorResponse。

you can use it like this你可以像这样使用它

    saveLocationNew(request: AddLocationRequest, entityId:string, userId:string): Observable<AddLocationResponse> {

      return this.httpClient.post<AddLocationResponse>(this.addLocationUrl, request ,  {headers:Constants.getHeaders(userId,entityId)})
      .pipe(
    tap(_ => console.log('creating a new location')),
    catchError(this.handleError<string>('stats')))
  )
}

now create function named handle error to handle all error requests like this现在创建一个名为 handle error 的函数来处理所有这样的错误请求

private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);   
      console.log(`${operation} failed: ${error.message}`);
      if(error.error.message == "Token is invalid!"){
        localStorage.removeItem('token');
        this.router.navigateByUrl('/login');
      }
      else{
        return throwError(error)
      }
      return of(result as T);
    };
  }

you need to throw that error if you want to deal with that error in your component.如果您想在组件中处理该错误,则需要抛出该错误。 hope this will help you.希望这会帮助你。

我从源代码中删除了 HttpClientModule 的多个定义,并且能够让一切正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM