首页 > 解决方案 > 如何通过 HttpInterceptor 映射 HttpResponseError 值?

问题描述

我在nodejs中使用Angularnodejs;我以自定义格式包装错误,例如:

服务器/路由/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
    }
)

所以,我想用maprxjs/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

标签: angularrxjs

解决方案


你能试试这个,并用日志更新我

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);
                        }));

                  }
    );

推荐阅读