You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Interceptor中Rxjs catchError无法获取后端自定义异常信息问题

Angular拦截器统一捕获后端自定义异常解决方案

核心原因

你在catchError中无法获取自定义异常,是因为Angular封装的HTTP错误响应对象HttpErrorResponse会将后端返回的原始异常内容挂载在error属性下,你需要从该属性中读取自定义信息而非直接读取错误对象本身。

1. 实现拦截器逻辑

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';

@Injectable()
export class CustomErrorInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        // 此处读取后端返回的自定义异常内容
        const customErrorInfo = error.error;
        console.log('拦截器获取到的自定义异常:', customErrorInfo);
        
        // 在此处编写统一错误处理逻辑,例如全局弹窗提示、401状态跳转到登录页等
        if (error.status === 401) {
          // 未授权跳转逻辑
        }

        // 处理完成后将错误抛出,不影响业务代码subscribe的error回调做个性化处理
        return throwError(() => error);
      })
    );
  }
}

2. 注册拦截器

在app.module.ts的providers数组中添加拦截器注册配置:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { CustomErrorInterceptor } from './custom-error.interceptor';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomErrorInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

注意事项

  • 若后端返回JSON结构的自定义异常,可直接通过error.error.xxx读取对应字段,例如错误提示信息可取值error.error.message
  • 没有特殊需求不要在拦截器中吞掉错误不抛出,否则会导致业务代码的error回调无法收到异常信息
  • 存在多个拦截器的场景下,建议将错误处理拦截器放在注册列表的最前面,避免其他拦截器修改原始错误内容

内容的提问来源于stack exchange,提问作者Álvaro Blázquez Sarabia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:27:03