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

Angular中HttpErrorInterceptor如何展示非404的后端自定义错误消息

解决方案:调整HttpErrorInterceptor以传递后端自定义错误信息

问题根源

当前拦截器将所有错误转换为字符串抛出,导致组件无法访问原始HttpErrorResponse对象中的error.customErrorMessage字段。我们需要修改拦截器,保留错误对象的结构,同时按需替换或补充错误信息。

调整后的拦截器代码

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

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
        .pipe(
            retry(1),
            catchError((error: HttpErrorResponse) => {
              // 保留原始错误对象结构,仅按需修改信息
              let modifiedError = {...error};

              if (error.error instanceof ErrorEvent) {
                // 客户端错误:格式化消息
                modifiedError.message = `客户端错误: ${error.error.message}`;
                modifiedError.error = {
                  customErrorMessage: modifiedError.message
                };
              } else {
                // 服务端错误
                if (error.status === 404) {
                  // 404返回固定提示
                  modifiedError.error = {
                    customErrorMessage: '资源未找到'
                  };
                  modifiedError.message = '资源未找到';
                } else {
                  // 优先使用后端返回的customErrorMessage,否则使用默认格式
                  const customMsg = error.error?.customErrorMessage || 
                    `错误码: ${error.status}\n消息: ${error.message}`;
                  modifiedError.error = {
                    ...error.error,
                    customErrorMessage: customMsg
                  };
                  modifiedError.message = customMsg;
                }
              }

              return throwError(() => modifiedError);
            }),
        );
  }
}

export const ErrorInterceptorProvider = {
  provide: HTTP_INTERCEPTORS,
  useClass: HttpErrorInterceptor,
  multi: true,
};

组件代码修正(语法错误及逻辑调整)

原组件存在语法错误,同时需要正确获取自定义错误信息:

import { Component } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  loading: boolean = false;
  error: string = '';
  customErrorMessage: string = ''; // 声明该变量

  constructor(private userService: UserService) {}

  getUsers() {
    this.loading = true;
    this.error = '';
    this.customErrorMessage = '';

    this.userService.getUsers().subscribe(
      users => {
        console.log(users);
        this.loading = false;
      },
      // 修正错误回调的语法
      (err) => {
        // 优先获取自定义错误信息
        if (err.error?.customErrorMessage) {
          this.customErrorMessage = err.error.customErrorMessage;
          this.error = err.message;
        } else {
          this.error = err.message;
        }
        this.loading = false;
      }
    );
  }
}

关键改动说明

  1. 保留错误对象结构:不再将错误转换为字符串抛出,而是修改原始HttpErrorResponse对象,确保组件能访问err.error下的字段。
  2. 404错误处理:为404错误主动添加customErrorMessage字段,保持与其他错误的结构一致性。
  3. 自定义信息优先级:对于非404的服务端错误,优先使用后端返回的customErrorMessage,不存在时再使用默认格式拼接的消息。
  4. 客户端错误兼容:格式化客户端错误信息并添加到customErrorMessage字段,统一组件处理逻辑。

内容的提问来源于stack exchange,提问作者Learner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:35:21