angular - Angular:拦截HTTP错误并继续链
问题描述
我想将某些 HTTP 错误代码视为非错误,并正常处理它们的响应。所以我尝试添加一个HttpInterceptor
来捕获 500 个状态代码,并返回原始响应(Angular 放入error.error
):
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 500) {
return of(error.error);
} else {
return throwError('server error');
}
})
);
}
但是,如果出现错误,我通过管道传输到我的 http 请求的任何内容都不会被执行。例如,如果我这样做,日志语句不会发生:
this.http.get(...).pipe(
tap(console.log)
)
我怎样才能使这项工作?
这是一个示例……它从不从 AppComponent 记录“得到结果”。
解决方案
你的链停止工作,因为 Angular http 模块过滤了它从拦截器接收到的消息:
const res$: Observable<HttpResponse<any>> = <Observable<HttpResponse<any>>>events$.pipe(
filter((event: HttpEvent<any>) => event instanceof HttpResponse));
如您所见,您应该返回HttpResponse
类流,例如:
import { HttpResponse, ... } from '@angular/common/http';
...
if (error.status === 404) {
console.log('caught', error.error);
return of(new HttpResponse({
body: error.error
}));
}
推荐阅读
- google-compute-engine - 无法在端口 22 上连接实例
- c# - 如何在 unity2d 编写正确的跳转脚本?刚体.addforce 不起作用
- uml - 继承与否?
- php - SQLSTATE [22007]:无效的日期时间格式:1292 不正确的日期时间值:第 1 行的列“created_at”的“1970-01-01 00:00:01”
- python - 简化处理当前使用 datetime 和 isodate 的时间和持续时间的代码?
- geoserver - 我可以直接从 Vertica 提供地图图层吗?
- php - 提交按钮以打开引导模式
- python - Python - ctypes - 访问缓冲区返回作为 dll 库中的指针 - 数据翻译 SDK
- python - 两条记录消息记录为一行
- sql-server - Excel 执行带参数的 SQL Server 存储过程