首页 > 解决方案 > Angular 和 RxJS - catchError() 不会捕获请求错误

问题描述

更新:我找到了问题。答案如下

我的服务类中有以下代码:

public getListById(id:string): Observable<any[]> {
        return this.http.get<any[]>(`${BASE_URL.local}/${id}`).pipe(
            map(obj => obj),
            catchError(error => this.handleError(error))
        )
    }

handleError(error: any): Observable<any> {
        console.log(error)
        this.snackBar.open(
            "Server Error",
            "X"
        )
        return EMPTY;
    }

以及我的组件中的以下代码:

this.myService.getListById(id).subscribe(
    res => { doSomethingWith(res) },
    error => { 
        this.noRows = true
        console.log(error)
    },
    () => { this.loading = false }
)

当服务在 Rest 地址中调用 GET 时,它会给出 500 错误,我想处理它。

但是由于某种原因,中的catchError()函数pipe()没有捕获错误,并且只运行中的() => { this.loading = false }代码subscribe()

这个糟糕的 RxJs 模块我做错了什么(说真的,我不喜欢它与后端请求一起工作的方式)我不能简单地处理请求错误?

谢谢你。

回答

我发现了这个问题。另一个以前的开发人员定义了一个错误拦截器,它没有按应有的方式工作。

我删除了ErrorInterceptor并定义了一个新的。我还修复了我的 'providers' 属性定义app.module.ts,它没有引用正确的 ErrorInterceptor 类。

标签: angulartypescriptrxjs

解决方案


这正是错误已被catchError.

handleError返回EMPTY这意味着在没有发出的情况下关闭流。并且因为流已关闭,您会看到this.loading = false

放在debugger前面console.log(error)并打开开发人员工具来检查变量,也许this.snackBar.open有问题。


推荐阅读