Angular4.3中的HttpInterceptor:拦截400错误响应
HttpInterceptor in Angular 4.3: Intercepting 400 error responses
我希望拦截 401 和其他错误以便做出相应的反应。这是我的拦截器:
import { LoggingService } from './../logging/logging.service';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class TwsHttpInterceptor implements HttpInterceptor {
constructor(private logger: LoggingService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.logger.logDebug(request);
return next.handle(request)
.do(event => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event);
}
});
}
}
虽然这适用于 200 个请求,它不会拦截错误响应
我在 chrome 的开发控制台中看到的是:
zone.js:2616 GET http://localhost:8080/backend/rest/wrongurl 404 (Not
Found)
或者这个
zone.js:2616 GET http://localhost:8080/backend/rest/url 401
(Unauthorized)
我希望我的拦截器能够处理这个问题。我错过了什么?
Http
将错误发送到 observable 的错误流中,因此您需要使用 .catch
捕获它们(您可以阅读有关此内容的更多信息 here)。
return next.handle(request)
.do(event => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event);
}
})
.catch(err => {
console.log('Caught error', err);
return Observable.throw(err);
});
这对您来说可能太晚了,但希望其他人会发现它有用...这也是重写上述 return 语句以记录错误响应的方法:
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event);
}
}, (error: any) => {
if (error instanceof HttpErrorResponse) {
this.logger.logDebug(error);
}
});
我正在使用相同的方法自动将所有 401 未经授权的响应直接发送到我们的注销方法(而不是在每次调用 http 时检查 401):
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// process successful responses here
}
}, (error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401) {
authService.logout();
}
}
});
它就像一个绝对的魅力。 :)
为了拦截angular6中的Http响应错误,我做了一个小技巧将Observable转换为Promise:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const obs = next.handle(req);
if (!window.navigator.onLine) {
// Handle offline error
this.messageService.showError('No Internet Connection');
return;
}
obs.toPromise().catch((error) => {
this.messageService.progress(false);
this.messageService.showError(error.message);
});
return obs;
}
当时我在尝试Angular7+.
Unfortunately above solutions did not serve the job well because .do
is not directly available on HttpHandler
as of RxJs 6 pipes notion; and converting Observable to Promise
does not stick.
这是最新的方法;我 pipe
catchError
运算符并分析错误,最后使用 throwError
重新抛出它。这是拦截器的最终形状;
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.error instanceof ErrorEvent) {
// client-side error or network error
} else {
// TODO: Clean up following by introducing method
if (error.status === 498) {
// TODO: Destroy local session; redirect to /login
}
if (error.status === 401) {
// TODO: Permission denied; show toast
}
}
return throwError(error);
})
);
}
希望这个解决方案对以后的人有所帮助。
我希望拦截 401 和其他错误以便做出相应的反应。这是我的拦截器:
import { LoggingService } from './../logging/logging.service';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class TwsHttpInterceptor implements HttpInterceptor {
constructor(private logger: LoggingService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.logger.logDebug(request);
return next.handle(request)
.do(event => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event);
}
});
}
}
虽然这适用于 200 个请求,它不会拦截错误响应
我在 chrome 的开发控制台中看到的是:
zone.js:2616 GET http://localhost:8080/backend/rest/wrongurl 404 (Not Found)
或者这个
zone.js:2616 GET http://localhost:8080/backend/rest/url 401 (Unauthorized)
我希望我的拦截器能够处理这个问题。我错过了什么?
Http
将错误发送到 observable 的错误流中,因此您需要使用 .catch
捕获它们(您可以阅读有关此内容的更多信息 here)。
return next.handle(request)
.do(event => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event);
}
})
.catch(err => {
console.log('Caught error', err);
return Observable.throw(err);
});
这对您来说可能太晚了,但希望其他人会发现它有用...这也是重写上述 return 语句以记录错误响应的方法:
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event);
}
}, (error: any) => {
if (error instanceof HttpErrorResponse) {
this.logger.logDebug(error);
}
});
我正在使用相同的方法自动将所有 401 未经授权的响应直接发送到我们的注销方法(而不是在每次调用 http 时检查 401):
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// process successful responses here
}
}, (error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401) {
authService.logout();
}
}
});
它就像一个绝对的魅力。 :)
为了拦截angular6中的Http响应错误,我做了一个小技巧将Observable转换为Promise:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const obs = next.handle(req);
if (!window.navigator.onLine) {
// Handle offline error
this.messageService.showError('No Internet Connection');
return;
}
obs.toPromise().catch((error) => {
this.messageService.progress(false);
this.messageService.showError(error.message);
});
return obs;
}
当时我在尝试Angular7+.
Unfortunately above solutions did not serve the job well because
.do
is not directly available onHttpHandler
as of RxJs 6 pipes notion; and convertingObservable to Promise
does not stick.
这是最新的方法;我 pipe
catchError
运算符并分析错误,最后使用 throwError
重新抛出它。这是拦截器的最终形状;
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.error instanceof ErrorEvent) {
// client-side error or network error
} else {
// TODO: Clean up following by introducing method
if (error.status === 498) {
// TODO: Destroy local session; redirect to /login
}
if (error.status === 401) {
// TODO: Permission denied; show toast
}
}
return throwError(error);
})
);
}
希望这个解决方案对以后的人有所帮助。