在我的应用程序中,我计划以下列方式处理错误:
return this.http.delete<IPosition>(url, {observe: 'response', headers: params.headers, params: params.queryParams})
.flatMap<HttpResponse<IPosition>, Position>((resp) => {
if(this.verbose){console.log(resp)}
switch (resp.status){
case 200: { /* Response OK */
return Observable.of<Position>(this.positionMapper.mapInterfaceToObject(resp.body, Position) as Position)
//return Observable.of<Position[]>(this.mapIfcToObj(resp.body) as Position[])
}
case 400: { /* Bad request */
return Observable.throw(resp.body)
}
case 404: {
return Observable.throw(new Error('Requested for unexisting schedule ID: '+params.path.idPosition))
}
case 500:{ /* Server internal erorr */
return Observable.throw(new Error('Internal server error: ' + resp.statusText))
}
default: {
throw new Error(`${resp.status}: ${resp.statusText}`)
}
}
})
由于除了OK范围(&gt; = 200)之外的每个状态都被角度HttpServer拦截,这导致我的所有基于switch
的erorr处理过程从未到达。我尝试在catch
和get
之间使用flatMap
RxJS子句来简单地传递所有请求:
.catch((err, source) => {
return source
})
不幸的是,这并不像我预期的那样(虽然文档在经过一些研究后会这样说),导致整个请求被重新请求。
我也熟悉新interceptor
中HttpClient
的概念,但这并不能满足我的需求:我需要针对不同的HTTP API端点进行特定的错误处理(即有时404确实可能是一个错误的,但在其他情况下,我想收到空数组或空对象)
我很感激任何帮助
答案 0 :(得分:0)
HttpClient
将导致非2xx状态代码的所有API调用的结果视为错误。这意味着在调用httpClient.post/get/etc
时,在此场景中返回的observable将包含一个项目,作为错误。有关Observables的更多信息,请阅读this documentation。
作为您的问题的解决方案,您需要以这种方式处理它:
return this.http.delete<IPosition>(url, {observe: 'response', headers: params.headers, params: params.queryParams})
.map((resp:HttpResponse<IPosition>) => { // Will always be a success from the API's side
let position:IPosition = resp.body;
// Do your 200 case here
}).catch((err: HttpErrorResponse) => { // Errors are handled with catch
if( err instanceof HttpErrorResponse) {
switch(err.status) {
case 400: {
return Observable.throw(resp.error) // This is the body of the response
},
case 404: {
return Observable.throw(new Error('Requested for unexisting schedule ID: '+params.path.idPosition))
},
case 500:{
return Observable.throw(new Error('Internal server error: ' + resp.statusText))
}
}
}
return Observable.of(//Something generic that wasn't handled)
});