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

Angular 14:如何阻止Http错误拦截器显示后端API地址

Angular 14全局Http错误拦截器Toastr重复弹窗问题解决

你遇到的问题本质是拦截器同时处理了后端返回的业务错误信息和HttpErrorResponse自带的带URL的系统错误信息,导致Toastr触发两次弹窗。

问题根源

HttpErrorResponse的message字段默认会拼接请求的API地址(比如"Http failure response for https://xxx/api/login: 400 OK"),如果拦截器同时把error.error(业务错误,如"Invalid Credentials")和error.message都传给Toastr,就会弹出两条提示。

修复代码

修改拦截器,优先取后端返回的业务错误,仅当没有明确业务错误时,再生成不包含URL的简洁提示,并且确保只调用一次Toastr:

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

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(private toastr: ToastrService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        let errorText = '';

        // 区分客户端错误和服务端错误
        if (error.error instanceof ErrorEvent) {
          // 客户端侧错误(比如网络断开)
          errorText = `客户端错误: ${error.error.message}`;
        } else {
          // 服务端返回的错误:优先取业务错误内容
          if (error.error) {
            // 如果后端返回的是字符串格式的错误(如"Invalid Credentials")
            if (typeof error.error === 'string' && error.error.trim()) {
              errorText = error.error;
            } 
            // 如果后端返回的是JSON对象(比如{ msg: "Invalid Credentials" }),根据实际字段调整
            else if (error.error.msg) {
              errorText = error.error.msg;
            }
          }

          // 没有业务错误时,生成不含URL的通用提示
          if (!errorText) {
            errorText = `请求失败,状态码: ${error.status}`;
          }
        }

        // 只弹出一次错误提示
        this.toastr.error(errorText);
        return throwError(() => error);
      })
    );
  }
}

关键调整点

  1. 优先使用业务错误:优先读取error.error中的业务提示,这是后端返回给用户的真实错误信息
  2. 过滤URL信息:不再直接使用error.message,而是当没有业务错误时,仅显示状态码和通用提示,避免暴露API地址
  3. 单次弹窗:确保整个错误处理流程只调用一次toastr.error(),彻底解决重复弹窗问题

额外注意

如果你的后端错误返回格式不同(比如错误信息在error.message字段),需要对应调整代码中的字段读取逻辑,保证能正确拿到业务错误文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:30:57