如何在Angular中阻止浏览器控制台显示401未授权报错信息
Angular 8 屏蔽401响应控制台报错解决方案
原理说明
Angular HttpClient 默认会将4xx、5xx类的HTTP响应识别为错误,若没有主动捕获错误回调,错误会向上抛出到全局,触发浏览器控制台打印红色报错。只要主动捕获错误流,即可避免控制台输出报错。
方案1:单请求局部捕获(适合少量接口单独处理场景)
在请求的subscribe方法中补充error回调,主动捕获错误:
// 原未捕获错误的写法(会触发控制台报错) this.http.get('/your/node/api').subscribe(res => { // 处理成功响应 }) // 改进后写法 this.http.get('/your/node/api').subscribe({ next: (res) => { // 处理成功响应 }, error: (err) => { if(err.status === 401) { // 自定义401逻辑,例如跳转登录、提示身份过期等 } // 其他错误也可在此处按需处理 } })
方案2:全局拦截器统一处理(适合全项目接口通用处理场景)
通过Angular HttpInterceptor全局拦截所有HTTP响应,统一处理401错误,无需每个请求单独写捕获逻辑:
步骤1:创建错误处理拦截器
执行命令生成拦截器文件:ng generate interceptor interceptors/error-handle
步骤2:编写拦截器逻辑
修改生成的error-handle.interceptor.ts文件:
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http'; import { Observable, EMPTY } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable() export class ErrorHandleInterceptor implements HttpInterceptor { intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { return next.handle(request).pipe( catchError((error: HttpErrorResponse) => { if (error.status === 401) { // 全局401处理逻辑,例如清除本地token、跳转登录页等 } // 返回EMPTY即可终止错误流向上抛出,不会触发控制台报错 // 若需要上层请求单独处理错误,可改为 return throwError(() => error) return EMPTY; }) ); } }
步骤3:注册拦截器到根模块
在AppModule的providers数组中添加拦截器注册:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { ErrorHandleInterceptor } from './interceptors/error-handle.interceptor'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [ { provide: HTTP_INTERCEPTORS, useClass: ErrorHandleInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
注意事项
- 不建议通过修改浏览器全局错误捕获逻辑屏蔽报错,会导致其他正常业务报错被隐藏,不利于问题排查
- 401状态建议补充对应的用户提示,避免用户无感知操作失效
内容的提问来源于stack exchange,提问作者ALOK KUMAR
相关产品推荐
相关产品推荐

