[英]Angular and RxJS - catchError() wont catch the request error
UPDATE: I FOUND THE ISSUE.更新:我找到了问题。 THE ANSWER IS BELOW
答案如下
I have the following code in my service class:我的服务 class 中有以下代码:
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;
}
And the following code in my component:以及我的组件中的以下代码:
this.myService.getListById(id).subscribe(
res => { doSomethingWith(res) },
error => {
this.noRows = true
console.log(error)
},
() => { this.loading = false }
)
When the service calls GET in the Rest address, it is giving a 500 error and I would like do handle it.当服务在 Rest 地址中调用 GET 时,它会给出 500 错误,我想处理它。
But the catchError()
function in pipe()
, for some reason, doesn't catch the error and only runs the () => { this.loading = false }
code inside subscribe()
.但是由于某种原因,
pipe()
中的catchError()
function 没有捕获错误,并且仅在subscribe()
中运行() => { this.loading = false }
代码。
What am I doing wrong with this bad RxJs module (seriously, I don't like the way that it works with backend requests) that I can't simply handle a request error?这个糟糕的 RxJs 模块(说真的,我不喜欢它处理后端请求的方式)我做错了什么,我不能简单地处理请求错误?
Thank you.谢谢你。
ANSWER回答
I found the issue.我发现了这个问题。 Another previous developer defined an Error Interceptor that wasn't working as it should.
另一位之前的开发人员定义了一个错误拦截器,它没有按应有的方式工作。
I deleted the ErrorInterceptor
and defined a new one.我删除了
ErrorInterceptor
并定义了一个新的。 I also fixed the 'providers' property definition in my app.module.ts
, it wasn't referencing the correct ErrorInterceptor class as it should.我还修复了
app.module.ts
中的“提供者”属性定义,它没有引用正确的 ErrorInterceptor class 。
That's exactly a sign that the error has been caught by catchError
.这正是
catchError
已捕获错误的标志。
handleError
returns EMPTY
that means to close a stream without an emit. handleError
返回EMPTY
,这意味着关闭 stream 而不发出发射。 And because the stream has been closed you see this.loading = false
.由于 stream 已关闭,您会看到
this.loading = false
。
put debugger
before console.log(error)
and open developer tools to inspect variables, perhaps this.snackBar.open
has an issue.将
debugger
放在console.log(error)
之前并打开开发人员工具来检查变量,也许this.snackBar.open
有问题。
I know this is different but try to change the behavior like this:我知道这是不同的,但尝试改变这样的行为:
return this.http.get<any[]>(`${BASE_URL.local}/${id}`).pipe(
catchError(err => {
this.errorObject = err;
return throwError(err);
})
);
public errorObject = null;
by default set the error to null: this.errorObject = null;
默认设置错误为 null:
this.errorObject = null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.