使用 RxJS 中的 catchError 操作符来捕获错误信息。
示例代码:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError(error => {
if (error instanceof HttpErrorResponse) {
console.error(`Error status code: ${error.status}`);
} else {
console.error(`Error message: ${error.message}`);
}
return throwError(error);
})
);
}
}
这个例子中的 HttpInterceptor 会把每个请求都拦截下来,并使用 RxJS 的 catchError 操作符来捕获错误信息。如果错误信息是一个 HttpErrorResponse 对象,它会打印出错误的状态码,否则它会打印出错误信息。无论如何,该方法都会继续抛出错误,以便其他的错误处理器可以继续处理它。