Angular 2 http 结果的正确错误处理

Proper error handling for Angular 2 http result

我一直在使用 angular.io 文档中使用的 http 错误处理策略:

getHeroes () {
    return this.http.get(this._heroesUrl)
                    .map(res => <Hero[]> res.json().data)
                    .catch(this.handleError);
    }
    private handleError (error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

在某些情况下,我将收到 204 状态代码(无数据),而不是 JSON 响应。在这种情况下,直到无法通过 res.json() 解析结果时才会调用错误处理程序,因此传递给 handleError 的错误是 "error.json is not a function".

我如何查询响应流以检查 200(正常)状态代码或 "application/json" 的响应 header content-type,并向错误处理程序发出更多信号相关错误信息?

http .get('Some Url') .map(res => { 
// If request fails, throw an Error that will be caught 
if(res.statu != 200) { 
throw new Error('This request has failed ' + res.status); } // If everything went fine, return the response 
else {return res.json(); 
} })

这可能对您有所帮助。

这只是为了了解如何使用响应中的状态,您可以根据自己的需要进行修改。

仅针对非 200 代码抛出错误检查此 commit