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

Angular/TypeScript:如何获取HTTP请求失败的详细信息?

Angular HTTP错误:获取更详细的错误信息

在Angular中遇到服务不可用、CORS限制这类底层网络错误时,浏览器出于安全策略,不会把控制台里的net::ERR_CONNECTION_REFUSED、net::ERR_FAILED这类原始错误码直接暴露给前端代码,但你可以通过HttpErrorResponse的属性间接区分错误类型,给用户提供更精准的提示。

核心处理思路

当HttpErrorResponse的status为0时,说明是网络层面的错误(而非服务端返回的HTTP状态码错误),此时可以通过err.message字段里的特征文本判断具体错误场景:

  • CORS错误:message中会包含CORS policy相关描述
  • 服务连接失败:message中会包含Failed to fetch或Connection refused相关描述

改进后的错误处理代码

import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';

// ...

this.http.get<MyResponseType[]>(`${this.HOST}/path/to/resource?param=${param}`)
  .pipe(
    catchError((err: HttpErrorResponse) => {
      let errorMessage = '未知错误';

      // 处理网络类错误(status = 0)
      if (err.status === 0) {
        const errorMsg = err.message.toLowerCase();
        if (errorMsg.includes('cors')) {
          errorMessage = '跨域请求被阻止,请联系管理员检查服务端CORS配置';
        } else if (errorMsg.includes('failed to fetch') || errorMsg.includes('connection refused')) {
          errorMessage = '无法连接到服务,请检查服务是否正常运行';
        }
      } else {
        // 处理服务端返回的HTTP状态码错误
        errorMessage = `请求失败:${err.statusText}(状态码:${err.status})`;
      }

      // 记录详细错误日志用于排查
      console.error('错误详情:', err);
      return throwError(() => new Error(errorMessage));
    })
  ).subscribe({
    next: (config) => console.log('请求成功:', config),
    error: (err) => console.error('用户提示:', err.message)
  });

注意事项

  • 不同浏览器的错误描述文本可能略有差异,建议用toLowerCase()统一转小写后再匹配特征词,提升兼容性。
  • 无法直接获取控制台里的net::xxx错误码,这是浏览器的安全限制,只能通过上述间接方式判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:32:27