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

如何通过HttpInterceptor将HttpErrorResponse转到成功回调?

解决方案

要实现将错误转换为非错误HttpEvent,核心是不在catchError中抛出错误,而是返回一个包含错误信息的合法HttpEvent对象,让它进入Observable的next通道而非error通道,这样就能在同一个回调里接收成功和错误结果。

具体实现步骤

  1. 导入必要依赖:确保导入of用于创建Observable,以及HttpResponse(它是HttpEvent的子类)。
  2. 修改catchError逻辑:将HttpErrorResponse包装成一个自定义的HttpResponse,包含错误状态、消息和详情。
  3. 返回正常Observable:用of()包裹包装后的响应,替代throwError()。

完整拦截器代码

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

@Injectable()
export class ErrorToResponseInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<any> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        // 包装错误为HttpResponse对象
        const errorResponse = new HttpResponse({
          status: error.status,
          statusText: error.statusText,
          body: {
            success: false,
            message: error.message,
            errorDetails: error.error
          },
          headers: error.headers
        });
        // 返回正常Observable,不抛出错误
        return of(errorResponse);
      })
    );
  }
}

使用方式

订阅请求时,无需单独处理error回调,直接在next回调中通过响应体标记或状态码区分成功/错误:

this.http.get('/api/example').subscribe((response) => {
  // 通过body中的success字段判断
  if (response.body?.success === false) {
    console.error('请求失败:', response.body.message);
    // 执行错误处理逻辑
  } else {
    console.log('请求成功:', response.body);
    // 执行成功处理逻辑
  }

  // 或者通过状态码判断(4xx/5xx为错误)
  if (response.status >= 400) {
    console.error('请求出错:', response.body.errorDetails);
  }
});

关键说明

  • HttpResponse是HttpEvent的合法子类,返回它会让Observable进入正常的next流,不会触发error回调。
  • 可以根据需求自定义响应体结构,比如添加success标记、错误码等,方便业务层识别。

内容的提问来源于stack exchange,提问作者Dickens A S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:56:14