簡體   English   中英

使用 http 攔截器的錯誤處理在 Angular 中不起作用

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

我正在研究 Angular 8

我正在嘗試通過 Interceptor 集中處理錯誤

我的攔截器代碼正在運行,但沒有返回任何錯誤

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);
      }))
  }
} 

我還在 app.module.ts 的 Providers 中定義了攔截器

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

我收到的錯誤 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

確保您的 API 以以下格式返回 JSON 響應,

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

以下對我有用,(我在下面的示例中進行了tap ,以防您想從成功的 JSON 響應中提取某些內容)。

錯誤可以在catchError部分處理。 請參閱為403401提供的error.status示例。 隨意自定義該部分。

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);

  }

我希望這可以幫助別人。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM