简体   繁体   English

RXJS catchError 不捕获网络故障错误

[英]RXJS catchError does not catch network failure errors

I have a service method which makes an API post request for logging out of the application.我有一个服务方法,它发出 API 发布请求以注销应用程序。

public logout(): Observable<APIResponse | ResponseError> {
    return this.http
    .post<APIResponse>(API_ENDPOINT + LOGOUT_URL, '{}', this.httpHeaders)
    .pipe(catchError((error) => {
        return of(this.handleError(error.error));
    }));
}

The catchError catches all the other valid errors thrown from the server. catchError捕获从服务器抛出的所有其他有效错误。 However, when there's no network connection or when the server is down, it does not work.但是,当没有网络连接或服务器关闭时,它就不起作用。 What is interesting is the fact that, all these errors are properly caught by my interceptor which does some customised handling for specific responses.有趣的是,所有这些错误都被我的拦截器正确捕获,该拦截器对特定响应进行了一些自定义处理。

Can anyone tell me why it is working in interceptor but not in my service?谁能告诉我为什么它在拦截器中工作但不在我的服务中? I am using the same catchError operator in my interceptor too.我也在拦截器中使用相同的catchError运算符。

Here's the inereceptor这是不接收器

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.url.endsWith('/login')) {
        return next.handle(req);
    }
    const body = JSON.parse(<string>req.body);
    const copiedReq = req.clone({ body: body });
    return next.handle(copiedReq)
        .pipe(tap(evt => { }), catchError((err: any) => {
            if (err instanceof HttpErrorResponse) {
                const httpError: HttpErrorResponse = err;
                // Custom logic ...
            }
            return of(err);
        }));
}

If you use the same catchError in your interceptor, the behavior you describe is exactly what I would expect.如果您在拦截器中使用相同的catchError ,那么您描述的行为正是我所期望的。 In that case, the error is swallowed by your interceptor.在这种情况下,错误会被您的拦截器吞下。

.pipe(catchError((error) => {
    return of(this.handleError(error.error));
}));

The catchError catches any error on the Observable stream. catchError捕获 Observable stream 上的任何错误。 If an error arrives in your interceptor, it is catched and a new value is emitted on the Observable stream using of .如果一个错误到达你的拦截器,它会被捕获并在 Observable stream 上使用of

I would recommend to use throwError instead of of in your interceptor, because then the original error is emitted back on the Observable stream and eventually will arive in your service.我建议使用throwErrorof在您的拦截器中使用,因为原始错误会在 Observable stream 上发出回并最终到达您的服务中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM