拦截错误并订阅
问题描述:
我遇到了以正确方式订阅我的http拦截器的问题。我有以下几点:拦截错误并订阅
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{
return super.post(url,body, {headers: customHeaders}).catch(err =>{
console.log('Error caught in POST at '+url);
return Observable.of(err);
});
}
这是好的 - 它记录每次发布时发生错误。但是,如果我试图抓住错误在其他组件是这样的:
this.http.post('someurl','somestring')
.subscribe(
success=>{
console.log('success: ',success);
},
error=>{
console.log('error: ',error);
}
)
所以现在,当在POST的错误我的控制台日志打印:
Error caught in POST at someurl
success: //errorobject here//
不过,我期待这样的:
Error caught in POST at someurl
error: //errorobject here//
我在做什么错?
答
我觉得应该是throw err
而不是Observable.of(err)
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{
return super.post(url,body, {headers: customHeaders}).catch(err =>{
console.log('Error caught in POST at '+url);
throw err;
});
}
答
我会用Observable.throw
,而不是Observable.of
:
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{
return super.post(url,body, {headers: customHeaders}).catch(err =>{
console.log('Error caught in POST at '+url);
return Observable.throw(err); // <--------------
});
}
Observable.of
返回一个“成功”可观察则其将被成功处理在subscribe
内回调。
蒂埃里,我为你去了一个http://stackoverflow.com/questions/37049848/http-stream-send-twice-instead-of-once :) – uksz