import _ from 'lodash'; type IErrorEventHandlerConstructData = { apiUrl: string; }; interface IErrorEventHandler { handle(event: ErrorEvent): void; } class ErrorEventHandler implements IErrorEventHandler { #headers: Headers; #apiUrl: string; #handledErrors: Set = new Set(); constructor(data: IErrorEventHandlerConstructData) { const { apiUrl } = data ?? {}; if (!_.isString(apiUrl) || _.isEmpty(apiUrl)) { throw new Error('[ErrorMessageHandler] constructor: please provide a valid apiUrl'); } this.#apiUrl = apiUrl; this.#headers = new Headers({ Accept: 'application/json', 'Content-Type': 'application/json' }); } handle(error: ErrorEvent): void { const { message, filename, lineno, colno } = error; const hash = `${message}${filename}${lineno}${colno}`; if (this.#handledErrors.has(hash)) { return; } this.#handledErrors.add(hash); fetch(`${this.#apiUrl}/ui/error-log`, { method: 'PUT', headers: this.#headers, body: JSON.stringify({ filename: error.filename, message: error.message, line: error.lineno, column: error.colno, stack: error.error?.stack }) }).catch((error) => { // eslint-disable-next-line no-console console.warn('Unable to send error to server', error); this.#handledErrors.delete(hash); }); return; } } export { ErrorEventHandler }; export type { IErrorEventHandler, IErrorEventHandlerConstructData };