angular - 如何通过 HttpInterceptor 映射 HttpResponseError 值?
问题描述
我在nodejs中使用Angular和nodejs;我以自定义格式包装错误,例如:
服务器/路由/data.route.js:
router.post('/data', (req, res) => {
getData().then(data => res.send(data))
.catch(errObj => res.status(errObj .status).send(errObj ));
});
这个 errObj 和我从nodejs返回的每个错误值都将采用以下格式:
{
title: 'cannot update document',
control: 'name',
status: 406,
desc: 'new doc is invalid name'
}
subscribe
因此,在Angular内部的每个错误回调中;我希望 errObj inside HttpErrorResponse
,例如:
src/app/app.component.ts
this.service.create(document).subscribe(
res => { ... },
error => {
// I have to rewrite this in each error callback
let errObj = error.error;
// do something
}
)
所以,我想用map
来rxjs/operators
直接映射错误HttpInterceptor
,比如:
// inside intercept function
return next.handle(req.clone()).pipe(
map(res => {
console.log(res);
return (res instanceof HttpErrorResponse)? res.error: res;
})
);
每次我在地图中记录 res 时,它都会打印:{type: 0}
,显然它不起作用。
我如何映射响应HttpInterceptor
?
解决方案
你能试试这个,并用日志更新我
return next.handle(req.clone()).pipe(
return next.handle(req).pipe(
tap(res=> {
if (res instanceof HttpResponse) {
console.log('We have response'); // Please look at this first
console.log(res); // Please look at this first
}
}),
catchError((err: any) => {
console.log('We have an error here')
return (err instanceof HttpErrorResponse)? err.error: of(err);
}));
}
);
推荐阅读
- python-3.x - 如何在python中从具有非重叠补丁大小32 X 32的图像中提取24维颜色直方图特征向量
- javascript - Nestjs 使用 axios
- angular - 通过孩子向孙子注入祖先的前向参考
- google-app-engine - 在 AppEngine 开发服务器上导入 matplotlib 失败
- azure-devops - 构建在管道中更改的功能分支
- html - 如何填充边距的整个背景颜色?
- https - 服务器和客户端在客户机器上运行,我应该使用 HTTPS,如何使用?
- amazon-web-services - 忽略自动生成的 AWS Amplify 文件
- swift - 为 ARKit(不是 QLPreview)材质属性加载 USDZ
- c# - 根据数组成员的其他属性,在 Unity 编辑器中显示数组成员的某些属性