我一直在使用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不是函数”。
如何查询响应流以检查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();
} })
这可能对您有帮助。
这只是为了了解如何使用响应中的状态,您可以根据需要进行修改。
仅针对非200代码抛出错误,请检查此提交
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句