如何使用Angular HttpClient从Rxjs Observable捕获无网络(无Internet连接)错误
RXJS捕获错误代码
.catch((err: HttpErrorResponse) => {
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', err.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
}
// ...optionally return a default fallback value so app can continue (pick one)
// which could be a default value
// return Observable.of<any>({my: "default value..."});
// or simply an empty observable
return Observable.empty<T>();
});
当用户没有网络并尝试发布API请求时,我试图捕获错误。在上面的代码中,它说err.error instanceof Error可以捕获任何网络错误,但不会。
同时使用Ios和Android模拟器,每当没有网络时,我会得到一个错误代码0和消息Unknown Error。我只能检查错误代码为0的时间,然后返回没有互联网连接的消息,但我无法确定这实际上是网络错误。
是否有任何方法可以确保错误是没有互联网连接问题?
当然,我可以在获取或发布api请求之前检查网络,但是随后我所有带有api请求的页面都需要持续监视网络连接。
答案 0 :(得分:0)
如果收到错误代码0,则可以使用navigator.onLine
作为附加检查。
尽管我不确定此变量的可靠性如何。