2016-12-28 68 views
7

error-handling ERR_CONNECTION_REFUSED展示如何如下处理错误:如何拉手网::在Angular2

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 

难道我这个根据状态的响应的处理?

+0

我也想知道为什么'ERR_CONNECTION_REFUSED'不能立即响应。有时候会发生一分钟后。 – niaomingjian

回答

2
//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']); 
} 
} 
+0

状态0是什么意思?我可以在哪里找到在线定义? – niaomingjian

+0

200至299之间的响应状态代码被视为成功状态,其他代码指示失败。更多详情:https://en.wikipedia.org/wiki/List_of_HTTP_status_codes – siva636

+1

我知道。但是什么是状态0?通常情况下,我将status 0视为其他编程语言的成功。 – niaomingjian