从Angular中的HttpInterceptor访问HTTP错误响应正文 [英] Accessing HTTP Error Response Body from HttpInterceptor in Angular
问题描述
我有一个HttpInterceptor来捕获错误并以模式显示它们.除了错误代码和消息,我还要显示响应的正文,该正文实际上包含对错误的更精确的描述(例如,关于500个内部服务器错误). 我怎样才能做到这一点呢? (我正在使用4.3.6版.)
I have an HttpInterceptor to catch errors and display them in a modal. Besides error code and message, I would also like to show the body of the response which actually holds a more precise description of the error (e.g. on a 500 internal server error). How can I achieve this in angular? (I am using version 4.3.6.)
我已经看过相关的问题,但是像HttpErrorResponse._body之类的答案对我却不起作用. 另外,在控制台中检查错误响应时,HttpErrorResponse.error设置为null.
I already looked at related questions but answers like HttpErrorResponse._body or similar don't work for me. Also, when inspecting the error response in the console, HttpErrorResponse.error is set to null.
这是我的拦截器当前的外观:
Here is how my interceptor currently looks:
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
public constructor(private httpErrorService: HttpErrorService) { }
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do(event => {
}, (error: HttpErrorResponse) => {
console.log('HTTPERROR INTERCEPTOR');
console.log(error);
if (error.status >= 400) {
this.httpErrorService.onError(error);
}
});
}
}
推荐答案
答案适用于低于6的Angular版本.
正文应该在error
属性中可用,所以:
The answer applies to versions of Angular below 6.
The body should be available in the error
property, so:
return next.handle(req).do(event => {
}, (error: HttpErrorResponse) => {
console.log(error.error); // body
...
});
这是实现的要旨从来源:
if (ok) {
...
} else {
// An unsuccessful request is delivered on the error channel.
observer.error(new HttpErrorResponse({
// The error in this case is the response body (error from the server).
error: body, <--------------------
headers,
status,
statusText,
url: url || undefined,
}));
}
要了解有关拦截器背后机制的更多信息,请阅读:
To learn more about mechanics behind interceptors read:
这篇关于从Angular中的HttpInterceptor访问HTTP错误响应正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!