如何统计API错误触发的/page-error访问并排除非API错误场景?
解决API错误触发的错误页面统计问题
可以通过以下几种方式区分API错误触发的/page-error访问和其他场景:
方案一:路由导航时传递状态标记
在拦截器中重定向时,通过navigationExtras添加状态标记,标识该跳转来自API错误:
// 拦截器代码修改 return next.handle(request.clone()).pipe( catchError((err: any) => { this.router.navigate(['/page-error'], { state: { fromApiError: true } // 添加来源标记 }); return throwError(() => err); // 修正原代码的变量错误 }) );
在AppComponent的路由监听中,仅当状态标记存在时才执行统计:
// AppComponent代码修改 router.events.pipe( distinctUntilChanged((previous: any, current: any) => { if (current instanceof NavigationEnd) { return previous.url === current.url; } return true; }), filter(current => current instanceof NavigationEnd && current.url === '/page-error') ) .subscribe((current: NavigationEnd) => { const navigation = this.router.getCurrentNavigation(); const isFromApiError = navigation?.extras.state?.fromApiError; if (isFromApiError) { // count as error and send it to GA } });
浏览器回退时路由状态不会保留,因此回退到错误页面不会触发统计,符合需求。
方案二:使用共享服务标记来源
创建共享服务存储跳转来源标记:
// error-navigation.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ErrorNavigationService { isFromApiError = false; }
在拦截器中设置标记:
// 拦截器代码修改 constructor(private router: Router, private errorNavService: ErrorNavigationService) {} return next.handle(request.clone()).pipe( catchError((err: any) => { this.errorNavService.isFromApiError = true; this.router.navigate(['/page-error']); return throwError(() => err); }) );
在PageErrorComponent中完成统计并立即重置标记:
// page-error.component.ts constructor(private errorNavService: ErrorNavigationService) {} ngOnInit() { if (this.errorNavService.isFromApiError) { // count as error and send it to GA // 重置标记,避免回退或其他操作误触发 this.errorNavService.isFromApiError = false; } }
这种方式无需监听全局路由事件,统计逻辑更精准。
方案三:拦截器内直接统计(最简洁)
既然API错误已在拦截器中捕获,可直接在这里执行统计,不依赖路由跳转事件:
// 拦截器代码修改 return next.handle(request.clone()).pipe( catchError((err: any) => { // 直接统计API错误 // count as error and send it to GA this.router.navigate(['/page-error']); return throwError(() => err); }) );
这种方式彻底避免了路由跳转带来的统计干扰,是最可靠的方案。
内容的提问来源于stack exchange,提问作者carlos
相关产品推荐
相关产品推荐

