简体   繁体   English

使用 http 拦截器的错误处理在 Angular 中不起作用

[英]error handling with http interceptor not working in Angular

I am working on Angular 8我正在研究 Angular 8

I am trying to centralise error handling through Interceptor我正在尝试通过 Interceptor 集中处理错误

My Interceptor code is running , but it is not returning any error我的拦截器代码正在运行,但没有返回任何错误

import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpResponse,
    HttpErrorResponse
   } from '@angular/common/http';
   import { Observable, throwError } from 'rxjs';
   import { retry, catchError } from 'rxjs/operators';
import { RestService } from './restservice';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';


@Injectable()
   export class HttpErrorInterceptor implements HttpInterceptor {

    constructor(private rest : RestService , private route : Router){}



    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      // console.log('jcsjdsjd');
      // console.error('xjxfjb');
      // console.log(request);
      // console.log(next);
      return next.handle(request).pipe(catchError(err => {
        console.log(err);
          if (err.status === 401) {
              // auto logout if 401 response returned from api
              // this.authenticationService.logout();
              location.reload(true);
          }

          const error = err.error.message || err.statusText;
          return throwError(error);
      }))
  }
} 

I have also defined interceptor in Providers of app.module.ts我还在 app.module.ts 的 Providers 中定义了拦截器

  providers: [RestService  , AuthGuard ,   commonRest    ,  {
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true
  }],

response that I am getting on request with error 403 is :我收到的错误 403 请求的响应是:

    {
  "messagecode": 403,
  "message": "not valid token!"
}

为了在全球范围内使用拦截器并且提供者在核心模块中,应该在拦截器的顶部添加 @Injectable({ providedIn: 'root' }) 像这里https://stackblitz.com/edit/angular-http-interceptor-working-for -lazy-loaded-module?file=src/app/core/token-interceptor.service.ts

Make sure your API returns JSON response in the following format,确保您的 API 以以下格式返回 JSON 响应,

{
   "status" : "403",
   "message" : "Session expired"
}

The following work for me, (I am having tap in the example below, in case if you want to extract something from a successful JSON response).以下对我有用,(我在下面的示例中进行了tap ,以防您想从成功的 JSON 响应中提取某些内容)。

The errors can be handled in the catchError section.错误可以在catchError部分处理。 See, provided error.status examples for 403 & 401 .请参阅为403401提供的error.status示例。 Feel free to customise that section.随意自定义该部分。

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

    return next.handle(request).pipe(
      tap(evt => {
        if (evt instanceof HttpResponse) {
          
        }
      }),
      catchError(err => {
        if (err.status === 403) {
          // Handle 403 specific errors
        } else if (err.status === 401) { 
          // Handle 401 specific errors
        }

        const error = err.error.message || err.statusText;
        return throwError(error);
      }), map(event => {
        if (event instanceof HttpResponse) {

        }
        return event;
      }), catchError(this.handleError));
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      // console.error(
      //   `Backend returned code ${error.status}, ` +
      //   `body was: ${error.error}`);

      // TODO :  do the logout here.
      // console.log(
      //   `Backend returned code ${error.status}, ` +
      //   `body was: ${error.error}`);
      // this.router.navigate(['/login'], { queryParams: { returnUrl: '' }});
    }
    // return an observable with a user-facing error message
    return throwError(error);

  }

I hope this helps someone.我希望这可以帮助别人。

Thanks.谢谢。

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

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