【发布时间】:2020-11-14 19:54:39
【问题描述】:
我有一个用例,由于模板问题,Angular 的错误处理程序被 25 多条错误消息轰炸。由于我的自定义错误处理程序正在使用远程记录器 (sentry.io),因此应用程序因对 sentry.io 的 API 请求过多而无响应。
现在我使用“懒惰的计时器”方法解决了这个问题,如下所示:
import { ErrorHandler, Injectable } from '@angular/core';
import { LoggingService } from './sentry.provider';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
private errorBuffer: Array<any>;
private lazyTimer: any;
constructor(private logger: LoggingService) {
this.errorBuffer = [];
};
handleError(error) {
this.errorBuffer.push(error);
this.processErrorBuffer();
};
private processErrorBuffer() {
if (this.lazyTimer) { clearTimeout(this.lazyTimer) };
this.lazyTimer = setTimeout(() => {
if (this.errorBuffer.length === 1) {
let error = this.errorBuffer.pop();
this.logger.reportError(error);
} else if (this.errorBuffer.length > 1) {
this.logger.reportError(this.errorBuffer);
this.errorBuffer = [];
};
}, 300)
};
}
所以基本上在每个错误之后而不是处理它我 setTimeout 它将执行错误处理逻辑或将被清除和更新(如果新错误在 300 毫秒内出现)。
这样我可以将单个错误发送到 Sentry 或批处理(数组)。
我尝试使用 RXJS 实现相同的逻辑,但未能找到方法。 我似乎不明白是哪个运营商执行这种定时器的更新。
那么我需要使用哪个运算符来使用 RXJS 复制此行为?
【问题讨论】:
-
您熟悉
debounceTime运算符吗?你也可以这样做。 -
是的,我查看了 debounceTime,但这只是给出了最后一个发出的值?我仍然需要捕获所有错误,而不仅仅是最后一个。至少看不到我如何在这种情况下使用 debounce 来处理发射值的爆发。或者您的意思是将所有错误存储在一个数组中并且只发出整个数组?
-
啊!您可以使用 debouceTime 和 ReplaySubject。有意义吗?
-
ReplaySubject 取最后编辑值的数量。让我研究一下,也许我可以找到一些东西来获取所有发出的值而不是最后一个。
-
是的,理想情况下,自上次去抖动“事件”以来发出的所有内容都是完美的。
标签: angular rxjs settimeout