test: improve ErrorUtils coverage
[e-mobility-charging-stations-simulator.git] / src / utils / ErrorUtils.ts
index f74c48e8859923ce0eec21976e3e60c089072239..0a444c6b1f5d945e5577dd7fbebc6ec235df16e6 100644 (file)
@@ -16,6 +16,8 @@ import type {
 import { logger } from './Logger.js'
 import { isNotEmptyString } from './Utils.js'
 
+const moduleName = 'ErrorUtils'
+
 const defaultErrorParams = {
   throwError: true,
   consoleOut: false
@@ -40,7 +42,7 @@ export const handleFileException = (
   logPrefix: string,
   params: HandleErrorParams<EmptyObject> = defaultErrorParams
 ): void => {
-  setDefaultErrorParams(params)
+  params = setDefaultErrorParams(params)
   const prefix = isNotEmptyString(logPrefix) ? `${logPrefix} ` : ''
   let logMsg: string
   switch (error.code) {
@@ -88,9 +90,9 @@ export const handleSendMessageError = (
     consoleOut: false
   }
 ): void => {
-  setDefaultErrorParams(params, { throwError: false, consoleOut: false })
+  params = setDefaultErrorParams(params, { throwError: false, consoleOut: false })
   logger.error(
-    `${chargingStation.logPrefix()} Send ${getMessageTypeString(messageType)} command '${commandName}' error:`,
+    `${chargingStation.logPrefix()} ${moduleName}.handleSendMessageError: Send ${getMessageTypeString(messageType)} command '${commandName}' error:`,
     error
   )
   if (params.throwError === true) {
@@ -98,10 +100,31 @@ export const handleSendMessageError = (
   }
 }
 
+export const handleIncomingRequestError = <T extends JsonType>(
+  chargingStation: ChargingStation,
+  commandName: IncomingRequestCommand,
+  error: Error,
+  params: HandleErrorParams<T> = { throwError: true, consoleOut: false }
+): T | undefined => {
+  params = setDefaultErrorParams(params)
+  logger.error(
+    `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
+    error
+  )
+  if (params.throwError === false && params.errorResponse != null) {
+    return params.errorResponse
+  }
+  if (params.throwError === true && params.errorResponse == null) {
+    throw error
+  }
+  if (params.throwError === true && params.errorResponse != null) {
+    return params.errorResponse
+  }
+}
+
 export const setDefaultErrorParams = <T extends JsonType>(
   params: HandleErrorParams<T>,
   defaultParams: HandleErrorParams<T> = defaultErrorParams
 ): HandleErrorParams<T> => {
-  params = { ...defaultParams, ...params }
-  return params
+  return { ...defaultParams, ...params }
 }