import * as Flex from '@twilio/flex-ui'; import { FlexPluginErrorContents, PluginConfig } from '../../types'; import { FlexErrorSeverity, FlexPluginErrorType } from '../../enums'; import datadogBrowserLogger from '../BrowserLogger'; export class FlexPluginError extends Error { public content: FlexPluginErrorContents & { type: FlexPluginErrorType | string; severity: FlexErrorSeverity; }; public time: Date; constructor(message: string, content: FlexPluginErrorContents = {}) { super(message); this.content = { ...content, type: content.type || 'LibraryPlugin', severity: content.severity || FlexErrorSeverity.error, }; this.time = new Date(); Object.setPrototypeOf(this, FlexPluginError.prototype); } } export class ErrorManager { private pluginConfig: PluginConfig; constructor(pluginConfig: PluginConfig) { this.pluginConfig = pluginConfig; } public processError(error: FlexPluginError, showNotification: boolean): FlexPluginError { try { console.log( `Library Plugin (${this.pluginConfig.name} @${this.pluginConfig.version}): ${error}\n` + `Type: ${error.content.type}\nContext: ${error.content.context}` ); console.error(error.message, error.content.wrappedError) const pluginError = new Flex.FlexError(error.message, { plugin: { name: this.pluginConfig.name, version: this.pluginConfig.version }, description: error.content.description, }); const currentFlexManager = window?.Twilio?.Flex?.Manager?.getInstance(); if (currentFlexManager?.reportErrorEvent) { currentFlexManager.reportErrorEvent(pluginError); } if (showNotification) { Flex.Notifications.showNotification('LibraryPlugin', { error }); } } catch (e) { // Avoid error propagation } return error; } public createAndProcessError( message: string, content: FlexPluginErrorContents = {}, showNotification = true, ): FlexPluginError { const error = new FlexPluginError(message, content); if (content.type !== FlexPluginErrorType.serverless) { const logErrorData = { type: content.type, severity: content.severity, context: content.context, wrappedError: content.wrappedError, description: content.description, pluginNme: this.pluginConfig.name, pluginVersion: this.pluginConfig.version, time: new Date().toISOString(), message } datadogBrowserLogger?.error("PLUGIN ERROR - ", logErrorData); } return this.processError(error, showNotification); } }