如何访问拦截器内部的错误响应主体?
How to access error response body inside of an interceptor?
我使用拦截器嗅探所有 HTTP requests/responses。
如果服务器 returns http 400,Angular 引发异常并且在 catch 块中我无法获取正文消息,如何获取正文响应:
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
console.log(error.body); // There is not body object here
});
在我的项目中,我使用 '@angular/common/http'
中的 HttpErrorResponse
来实现这一点
例如:
this.http.get('url').subscribe( response => {
}, (err: HttpErrorResponse) => {
if (err.status === 401 || err.status === 404) {
// do stuff
}
}
希望对您有所帮助
这是一个示例,您可以如何在 Interceptor
的帮助下完成此操作
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(error => this.handleError(error))
);
}
private handleError(error: HttpErrorResponse): Observable<any> {
if (error.status === 400) {
// Do your thing here
}
}
希望对你有所帮助。
我使用拦截器嗅探所有 HTTP requests/responses。
如果服务器 returns http 400,Angular 引发异常并且在 catch 块中我无法获取正文消息,如何获取正文响应:
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
console.log(error.body); // There is not body object here
});
在我的项目中,我使用 '@angular/common/http'
中的 HttpErrorResponse
来实现这一点
例如:
this.http.get('url').subscribe( response => {
}, (err: HttpErrorResponse) => {
if (err.status === 401 || err.status === 404) {
// do stuff
}
}
希望对您有所帮助
这是一个示例,您可以如何在 Interceptor
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(error => this.handleError(error))
);
}
private handleError(error: HttpErrorResponse): Observable<any> {
if (error.status === 400) {
// Do your thing here
}
}
希望对你有所帮助。