我一直在使用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');
}
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,我将收到204状态代码(无数据),而不是JSON响应.在这种情况下,错误处理程序不会被调用,直到无法通过解析的结果res.json(),所以传递到的HandleError错误是"error.json不是一个函数".
如何查询响应流以检查200(OK)状态代码或响应头内容类型"application/json",并通过更相关的错误消息发出错误处理程序的信号?
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();
} })
Run Code Online (Sandbox Code Playgroud)
这可能对你有所帮助.
这只是为了了解如何使用响应中的状态,您可以根据您的要求进行修改.
仅对非200代码检查此提交引发错误
| 归档时间: |
|
| 查看次数: |
14045 次 |
| 最近记录: |