refactor(simulator): factor out common helpers
[e-mobility-charging-stations-simulator.git] / src / utils / ErrorUtils.ts
index 0589fa194037a5017fd889e162fca35f6d87de75..7efbe514cab80209f24befc9b6eb565ca9083cb5 100644 (file)
@@ -2,13 +2,32 @@ import chalk from 'chalk';
 
 import { logger } from './Logger';
 import { Utils } from './Utils';
-import type { EmptyObject, FileType, HandleErrorParams } from '../types';
+import type { ChargingStation } from '../charging-station';
+import type {
+  EmptyObject,
+  FileType,
+  HandleErrorParams,
+  IncomingRequestCommand,
+  RequestCommand,
+} from '../types';
 
 export class ErrorUtils {
   private constructor() {
     // This is intentional
   }
 
+  public static handleUncaughtException(): void {
+    process.on('uncaughtException', (error: Error) => {
+      console.error(chalk.red('Uncaught exception: '), error);
+    });
+  }
+
+  public static handleUnhandledRejection(): void {
+    process.on('unhandledRejection', (reason: unknown) => {
+      console.error(chalk.red('Unhandled rejection: '), reason);
+    });
+  }
+
   public static handleFileException(
     file: string,
     fileType: FileType,
@@ -40,4 +59,16 @@ export class ErrorUtils {
       throw error;
     }
   }
+
+  public static handleSendMessageError(
+    chargingStation: ChargingStation,
+    commandName: RequestCommand | IncomingRequestCommand,
+    error: Error,
+    params: HandleErrorParams<EmptyObject> = { throwError: false }
+  ): void {
+    logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
+    if (params?.throwError === true) {
+      throw error;
+    }
+  }
 }