在拦截器抛出错误后,我们可以通过检查错误的类型来确定出现了什么问题。以下是一个Angular拦截器的示例代码,演示了如何检查错误的类类型:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401) {
// 处理未经授权的错误
} else if (error.status === 404) {
// 处理未找到的错误
} else if (error.status === 500) {
// 处理服务器错误
} else {
// 处理其他错误
}
} else {
// 处理非HttpErrorResponse类型的错误
}
return throwError(error);
})
);
}
}
在上述示例中,我们使用instanceof
操作符检查错误是否为HttpErrorResponse
类型。然后,我们可以根据错误的status
属性来执行不同的操作,例如处理未经授权的错误,处理未找到的错误,处理服务器错误等。如果错误不是HttpErrorResponse
类型,我们可以执行其他逻辑来处理非HTTP错误。
请注意,我们使用catchError
操作符捕获拦截器中的错误,并使用throwError
操作符将错误重新抛出,以便在调用方继续处理错误。
在应用中使用该拦截器,可以在模块或提供商配置中将其添加为HTTP_INTERCEPTORS
提供商:
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './error.interceptor';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
]
})
export class AppModule { }
这样,拦截器将在每个HTTP请求中处理错误,并根据错误的类型执行相应的操作。