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

在Angular v19中如何使用httpResource捕获请求错误?

在Angular v19中如何使用httpResource捕获请求错误?

嘿,我刚在Angular 19里折腾过httpResource的错误捕获,给你分享几个实用的路子~

方法一:在httpResource流中直接捕获错误

httpResource返回的是Observable,所以我们可以用RxJS的catchError操作符在数据流里直接拦截处理错误。先看修改后的服务代码:

import { Injectable } from '@angular/core';
import { httpResource, ResourceConfig } from '@angular/common/http';
import { catchError, of } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class MyService {
    resourceConfig = signal<Partial<ResourceConfig>>({})
    
    // 给httpResource添加错误捕获管道
    response = httpResource(() => ({
        url: this.resourceConfig().path as string,
        method: this.resourceConfig().method as string,
        body: this.resourceConfig().payload
    })).pipe(
        catchError((error: HttpErrorResponse) => {
            // 根据错误类型做自定义处理
            if (error.status === 401) {
                console.error('未授权,请重新登录');
                // 这里可以跳转到登录页,比如用Router
                // this.router.navigate(['/login']);
            } else if (error.status === 404) {
                console.error('请求的资源不存在');
            } else {
                console.error('请求出错啦:', error.message);
            }
            // 返回一个默认值或空Observable,避免订阅者崩溃
            return of(null);
        })
    )

    connect(payload: unknown) {
        this.resourceConfig.set({
            path: 'api/data',
            method: 'POST',
            payload: payload
        })
    }
}

方法二:在订阅时处理错误

如果不想在服务层统一处理错误,也可以在组件订阅response的时候,通过订阅对象的error回调来捕获:

import { Component } from '@angular/core';
import { MyService } from './my.service';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-root',
  template: `<button (click)="sendRequest()">发送请求</button>`
})
export class AppComponent {
  constructor(private myService: MyService) {}

  sendRequest() {
    this.myService.response.subscribe({
      next: (data) => {
        console.log('拿到数据啦:', data);
        // 处理正常返回的数据
      },
      error: (error: HttpErrorResponse) => {
        // 这里专门处理错误
        alert(`请求失败:${error.message}`);
        console.error('订阅时捕获到错误:', error);
      },
      complete: () => {
        console.log('请求完成啦');
      }
    });
    
    // 触发请求配置更新
    this.myService.connect({ username: 'test' });
  }
}

小贴士:利用HttpErrorResponse获取详细错误信息

不管用哪种方法,HttpErrorResponse对象里都包含了丰富的错误细节:

  • error.status:HTTP状态码(比如404、500)
  • error.message:错误描述信息
  • error.error:服务器返回的错误响应体(如果有的话)

你可以根据这些信息做更精细化的错误处理,比如给用户显示不同的错误提示,或者做自动化的重试逻辑。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 12:43:04