错误处理显示如何处理错误,如下所示:
private handleError (error: Response | any) {
  // In a real world app, we might use a remote logging infrastructure
  let errMsg: string;
  if (error instanceof Response) {
    const body = error.json() || '';
    const err = body.error || JSON.stringify(body);
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  console.error(errMsg);
  return Promise.reject(errMsg);
}
我想访问API服务器,但服务器尚未启动.然后我得到了错误:
http://localhost:3000/api/heroes net::ERR_CONNECTION_REFUSED
我需要礼貌地告诉用户API服务器还没有启动.我该如何处理错误?
错误响应是:
_body:ProgressEvent
headers:Headers
ok:false
status:0
statusText:""
type:3
url:null
我可以根据回复的状态来处理吗?
不可能区分 ERR_CONNECTION_TIMED_OUT (上面提到的那个)和 ERR_CONNECTION_REFUSED,因为 HttpErrorResponse 类不区分它们。因此,您必须使用状态 0 来处理所有一般错误。根据 HTTP 状态代码列表https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
如果您收到的响应不在此列表中,则它是非标准响应,可能是服务器软件自定义的。
这意味着 0 是非标准响应。
Angular 是一个 Javascript 框架;因此,您应该参考 XMLHttpRequest 状态代码来了解 0 的含义。Mozilla 页面说..
在请求完成之前,status 的值为 0。如果出现 XMLHttpRequest 错误,浏览器也会报告 status 0。
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status
因此,ERR_CONNECTION_REFUSED 表示连接未建立(请求未完成),因此状态代码为 0。在这种情况下,可以安全地说“无法连接到服务器”。throwError 是一个发出错误消息的 RxJs 函数,您可以通过 Subscribe() 方法读取该消息。
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((errorResponse: HttpErrorResponse) => {
       if (errorObj instanceof HttpErrorResponse) {
        if (errorObj.status === 0) {
          return throwError('Unable to Connect to the Server');
        }
       }
      })
    );
  }
//First inject the router in the constructor
private handleError (error: Response | any) {
//Your other codes    
if (error.status == 0){ //or whatever condition you like to put
this.router.navigate(['/error']);
}
}
| 归档时间: | 
 | 
| 查看次数: | 19087 次 | 
| 最近记录: |