API响应错误时如何在Angular Interceptor中获取所有http响应

时间:2019-03-28 09:24:26

标签: angular angular-http-interceptors

在处理错误响应时获取完整的http标头存在问题。

事实问题序言:

在发生错误(在我们的情况下为X-Message)时,或者在一切正常但存在一些包含有用信息的附加消息时,Api添加新标头参数

response.headers['X-Message'] = 'A user has no permissions to approve smth'

response.headers['X-Message'] = 'You've approved smth successfully, but...'

在客户端(Angular应用)上,它由拦截器处理:

return next.handle(request)
    .pipe(
        map((event: HttpEvent<any>) => {

            if (event instanceof HttpResponse) {
                this.notificationHandler.handle(event);
            }
            return event;
        }), 

    catchError((error: HttpErrorResponse) => {

        /*
        Problem is here!!!
        I need to get the response headers to
        read 'X-Message', but it's unavailable.
        */

        this.notificationHandler.handle(error);
        return throwError(error);
    });

问题出在哪里?response.status200时,一切正常。我可以获取并显示适当的标题字段。但是状态为400或更多时,所需的标头不可用

当在catchError句柄中需要完整的标头列表时,您是否遇到了某些问题?

感谢!

1 个答案:

答案 0 :(得分:0)

Angular具有内置的错误处理程序类。那抓住了所有的错误。 https://angular.io/api/core/ErrorHandler

相关问题