convertToDate,
convertToInt,
DCElectricUtils,
+ ensureError,
exponentialDelay,
formatDurationMilliSeconds,
formatDurationSeconds,
+ getErrorMessage,
getWebSocketCloseEventStatusString,
handleFileException,
isEmpty,
handleFileException(
this.configurationFile,
FileType.ChargingStationConfiguration,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
this.logPrefix()
)
if (
handleFileException(
this.templateFile,
FileType.ChargingStationTemplate,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
this.logPrefix()
)
}
const ocppError =
error instanceof OCPPError
? error
- : new OCPPError(
- ErrorType.INTERNAL_ERROR,
- error instanceof Error ? error.message : String(error)
- )
+ : new OCPPError(ErrorType.INTERNAL_ERROR, getErrorMessage(error))
switch (messageType) {
case MessageType.CALL_ERROR_MESSAGE:
case MessageType.CALL_RESULT_MESSAGE:
handleFileException(
this.configurationFile,
FileType.ChargingStationConfiguration,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
this.logPrefix()
)
})
handleFileException(
this.configurationFile,
FileType.ChargingStationConfiguration,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
this.logPrefix()
)
}
import type { ChargingStationInfo, ChargingStationWorkerData } from '../types/index.js'
import { BaseError } from '../exception/index.js'
-import { Configuration } from '../utils/index.js'
+import { Configuration, getErrorMessage } from '../utils/index.js'
import { type WorkerDataError, type WorkerMessage, WorkerMessageEvents } from '../worker/index.js'
import { ChargingStation } from './ChargingStation.js'
parentPort?.postMessage({
data: {
event,
- message: error instanceof Error ? error.message : String(error),
+ message: getErrorMessage(error),
name: error instanceof Error ? error.name : 'UnknownError',
stack: error instanceof Error ? error.stack : undefined,
},
import { FileType, IdTagDistribution } from '../types/index.js'
import {
+ ensureError,
handleFileException,
isNotEmptyString,
logger,
try {
return JSON.parse(readFileSync(file, 'utf8')) as string[]
} catch (error) {
- handleFileException(
- file,
- FileType.Authorization,
- error instanceof Error ? error : new Error(String(error)),
- this.logPrefix(file)
- )
+ handleFileException(file, FileType.Authorization, ensureError(error), this.logPrefix(file))
}
}
return []
handleFileException(
file,
FileType.Authorization,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
this.logPrefix(file),
{
throwError: false,
type StopTransactionRequest,
type StopTransactionResponse,
} from '../../types/index.js'
-import { Constants, convertToInt, isAsyncFunction, isEmpty, logger } from '../../utils/index.js'
+import {
+ Constants,
+ convertToInt,
+ getErrorMessage,
+ isAsyncFunction,
+ isEmpty,
+ logger,
+} from '../../utils/index.js'
import { getConfigurationKey } from '../ConfigurationKeyUtils.js'
import { buildMeterValue } from '../ocpp/index.js'
import { WorkerBroadcastChannel } from './WorkerBroadcastChannel.js'
responsePayload = {
command,
errorDetails: error instanceof OCPPError ? error.details : undefined,
- errorMessage: error instanceof Error ? error.message : String(error),
+ errorMessage: getErrorMessage(error),
errorStack: error instanceof Error ? error.stack : undefined,
hashId: this.chargingStation.stationInfo?.hashId,
requestPayload,
Configuration,
convertToDate,
convertToInt,
+ ensureError,
formatDurationMilliSeconds,
handleIncomingRequestError,
isEmpty,
return handleIncomingRequestError<GenericResponse>(
chargingStation,
OCPP16IncomingRequestCommand.CANCEL_RESERVATION,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
{
errorResponse: OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED,
}
return handleIncomingRequestError<OCPP16DataTransferResponse>(
chargingStation,
OCPP16IncomingRequestCommand.DATA_TRANSFER,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
{ errorResponse: OCPP16Constants.OCPP_DATA_TRANSFER_RESPONSE_REJECTED }
)!
}
return handleIncomingRequestError<GetDiagnosticsResponse>(
chargingStation,
OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
{ errorResponse: OCPP16Constants.OCPP_RESPONSE_EMPTY }
)!
}
return handleIncomingRequestError<OCPP16ReserveNowResponse>(
chargingStation,
OCPP16IncomingRequestCommand.RESERVE_NOW,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
{ errorResponse: OCPP16Constants.OCPP_RESERVATION_RESPONSE_FAULTED }
)!
}
HashAlgorithmEnumType,
InstallCertificateUseEnumType,
} from '../../../types/ocpp/2.0/Common.js'
+import { getErrorMessage } from '../../../utils/index.js'
/**
* Interface for ChargingStation with certificate manager
}
} catch (error) {
return {
- error: `Failed to store certificate: ${error instanceof Error ? error.message : String(error)}`,
+ error: `Failed to store certificate: ${getErrorMessage(error)}`,
success: false,
}
}
} from '../../types/index.js'
import {
clone,
+ ensureError,
formatDurationMilliSeconds,
handleSendMessageError,
logger,
chargingStation,
commandName,
MessageType.CALL_ERROR_MESSAGE,
- error instanceof Error ? error : new Error(String(error))
+ ensureError(error)
)
return null
}
chargingStation,
commandName,
MessageType.CALL_RESULT_MESSAGE,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
{
throwError: true,
}
chargingStation,
commandName,
MessageType.CALL_MESSAGE,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
{
throwError: params.throwError,
}
import { OCPPError } from '../../../../exception/OCPPError.js'
import { ErrorType } from '../../../../types/index.js'
import { OCPPVersion } from '../../../../types/ocpp/OCPPVersion.js'
-import { logger } from '../../../../utils/index.js'
+import { ensureError, getErrorMessage, logger } from '../../../../utils/index.js'
import { type ChargingStation } from '../../../ChargingStation.js'
import { AuthComponentFactory } from '../factories/AuthComponentFactory.js'
import {
timestamp: result.timestamp,
}
} catch (error) {
- lastError = error instanceof Error ? error : new Error(String(error))
+ lastError = ensureError(error)
logger.debug(
- `${this.chargingStation.logPrefix()} Strategy '${strategyName}' failed: ${error instanceof Error ? error.message : String(error)}`
+ `${this.chargingStation.logPrefix()} Strategy '${strategyName}' failed: ${getErrorMessage(error)}`
)
// Continue to next strategy unless it's a critical error
- if (this.isCriticalError(error instanceof Error ? error : new Error(String(error)))) {
+ if (this.isCriticalError(ensureError(error))) {
break
}
}
} catch (error) {
const duration = Date.now() - startTime
logger.error(
- `${this.chargingStation.logPrefix()} Direct authentication with ${strategyName} failed (${String(duration)}ms): ${error instanceof Error ? error.message : String(error)}`
+ `${this.chargingStation.logPrefix()} Direct authentication with ${strategyName} failed (${String(duration)}ms): ${getErrorMessage(error)}`
)
throw error
}
}
} catch (error) {
logger.debug(
- `${this.chargingStation.logPrefix()} Local authorization check failed: ${error instanceof Error ? error.message : String(error)}`
+ `${this.chargingStation.logPrefix()} Local authorization check failed: ${getErrorMessage(error)}`
)
}
}
} from '../interfaces/OCPPAuthService.js'
import type { AuthConfiguration, AuthorizationResult, AuthRequest } from '../types/AuthTypes.js'
-import { logger } from '../../../../utils/index.js'
+import { ensureError, getErrorMessage, logger } from '../../../../utils/index.js'
import {
AuthContext,
AuthenticationError,
)
return undefined
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`LocalAuthStrategy: Authentication error: ${errorMessage}`)
throw new AuthenticationError(
`Local authentication failed: ${errorMessage}`,
AuthErrorCode.STRATEGY_ERROR,
{
- cause: error instanceof Error ? error : new Error(String(error)),
+ cause: ensureError(error),
context: request.context,
identifier: request.identifier.value,
}
this.authCache.set(identifier, result, ttl)
logger.debug(`LocalAuthStrategy: Cached result for ${identifier}`)
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`LocalAuthStrategy: Failed to cache result: ${errorMessage}`)
// Don't throw - caching is not critical
}
this.isInitialized = true
logger.info('LocalAuthStrategy: Initialized successfully')
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`LocalAuthStrategy: Initialization failed: ${errorMessage}`)
throw new AuthenticationError(
`Local auth strategy initialization failed: ${errorMessage}`,
AuthErrorCode.CONFIGURATION_ERROR,
- { cause: error instanceof Error ? error : new Error(String(error)) }
+ { cause: ensureError(error) }
)
}
}
this.authCache.remove(identifier)
logger.debug(`LocalAuthStrategy: Invalidated cache for ${identifier}`)
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`LocalAuthStrategy: Failed to invalidate cache: ${errorMessage}`)
// Don't throw - cache invalidation errors are not critical
}
const entry = await this.localAuthListManager.getEntry(identifier)
return !!entry
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`LocalAuthStrategy: Error checking local list: ${errorMessage}`)
return false
}
logger.debug(`LocalAuthStrategy: Cache hit for ${request.identifier.value}`)
return cachedResult
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`LocalAuthStrategy: Cache check failed: ${errorMessage}`)
throw new AuthenticationError(
`Authorization cache check failed: ${errorMessage}`,
AuthErrorCode.CACHE_ERROR,
{
- cause: error instanceof Error ? error : new Error(String(error)),
+ cause: ensureError(error),
identifier: request.identifier.value,
}
)
timestamp: new Date(),
}
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`LocalAuthStrategy: Local auth list check failed: ${errorMessage}`)
throw new AuthenticationError(
`Local auth list check failed: ${errorMessage}`,
AuthErrorCode.LOCAL_LIST_ERROR,
{
- cause: error instanceof Error ? error : new Error(String(error)),
+ cause: ensureError(error),
identifier: request.identifier.value,
}
)
import type { AuthConfiguration, AuthorizationResult, AuthRequest } from '../types/AuthTypes.js'
import { OCPPVersion } from '../../../../types/ocpp/OCPPVersion.js'
-import { logger } from '../../../../utils/index.js'
+import { ensureError, getErrorMessage, logger } from '../../../../utils/index.js'
import {
AuthenticationError,
AuthenticationMethod,
this.stats.networkErrors++
}
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`RemoteAuthStrategy: Authentication error: ${errorMessage}`)
// Don't rethrow - allow other strategies to handle
logger.debug(`RemoteAuthStrategy: OCPP ${version} adapter configured`)
}
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(
`RemoteAuthStrategy: Configuration validation failed for OCPP ${version}: ${errorMessage}`
)
this.isInitialized = true
logger.info('RemoteAuthStrategy: Initialized successfully')
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`RemoteAuthStrategy: Initialization failed: ${errorMessage}`)
throw new AuthenticationError(
`Remote auth strategy initialization failed: ${errorMessage}`,
AuthErrorCode.CONFIGURATION_ERROR,
- { cause: error instanceof Error ? error : new Error(String(error)) }
+ { cause: ensureError(error) }
)
}
}
`RemoteAuthStrategy: Cached result for ${identifier.substring(0, 8)}... (TTL: ${String(cacheTtl)}s)`
)
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.error(`RemoteAuthStrategy: Failed to cache result: ${errorMessage}`)
// Don't throw - caching is not critical for authentication
}
clearTimeout(timeoutHandle)
return result
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
logger.debug(`RemoteAuthStrategy: Remote availability check failed: ${errorMessage}`)
return false
}
}
// Wrap other errors as network errors
- const errorMessage = error instanceof Error ? error.message : String(error)
+ const errorMessage = getErrorMessage(error)
throw new AuthenticationError(
`Remote authorization failed: ${errorMessage}`,
AuthErrorCode.NETWORK_ERROR,
{
- cause: error instanceof Error ? error : new Error(String(error)),
+ cause: ensureError(error),
context: request.context,
identifier: request.identifier.value,
}
type UIServerConfiguration,
type UUIDv4,
} from '../../types/index.js'
-import { generateUUID, JSONStringify, logger } from '../../utils/index.js'
+import { generateUUID, getErrorMessage, JSONStringify, logger } from '../../utils/index.js'
import { AbstractUIServer } from './AbstractUIServer.js'
import {
createBodySizeLimiter,
} catch (error) {
this.sendResponse(
this.buildProtocolResponse(uuid, {
- errorMessage: error instanceof Error ? error.message : String(error),
+ errorMessage: getErrorMessage(error),
errorStack: error instanceof Error ? error.stack : undefined,
status: ResponseStatus.FAILURE,
})
import { BaseError } from '../../exception/index.js'
import { Protocol, ProtocolVersion } from '../../types/index.js'
-import { isEmpty, logger, logPrefix } from '../../utils/index.js'
+import { getErrorMessage, isEmpty, logger, logPrefix } from '../../utils/index.js'
export const getUsernameAndPasswordFromAuthorizationToken = (
authorizationToken: string,
}
return [username, password]
} catch (error) {
- next(
- new BaseError(
- `Invalid basic authentication token format: ${error instanceof Error ? error.message : String(error)}`
- )
- )
+ next(new BaseError(`Invalid basic authentication token format: ${getErrorMessage(error)}`))
return undefined
}
}
type StorageConfiguration,
type UUIDv4,
} from '../../../types/index.js'
-import { Configuration, isAsyncFunction, isNotEmptyArray, logger } from '../../../utils/index.js'
+import {
+ Configuration,
+ ensureError,
+ getErrorMessage,
+ isAsyncFunction,
+ isNotEmptyArray,
+ logger,
+} from '../../../utils/index.js'
import { Bootstrap } from '../../Bootstrap.js'
import { UIServiceWorkerBroadcastChannel } from '../../broadcast-channel/UIServiceWorkerBroadcastChannel.js'
import { DEFAULT_MAX_STATIONS, isValidNumberOfStations } from '../UIServerSecurity.js'
responsePayload = {
command,
errorDetails: error instanceof OCPPError ? error.details : undefined,
- errorMessage: error instanceof Error ? error.message : String(error),
+ errorMessage: getErrorMessage(error),
errorStack: error instanceof Error ? error.stack : undefined,
hashIds: requestPayload?.hashIds,
requestPayload,
succeededStationInfos.push(stationInfo)
}
} catch (error) {
- err = error instanceof Error ? error : new Error(String(error))
+ err = ensureError(error)
if (stationInfo != null) {
failedStationInfos.push(stationInfo)
}
} satisfies ResponsePayload
} catch (error) {
return {
- errorMessage: error instanceof Error ? error.message : String(error),
+ errorMessage: getErrorMessage(error),
errorStack: error instanceof Error ? error.stack : undefined,
status: ResponseStatus.FAILURE,
} satisfies ResponsePayload
} satisfies ResponsePayload
} catch (error) {
return {
- errorMessage: error instanceof Error ? error.message : String(error),
+ errorMessage: getErrorMessage(error),
errorStack: error instanceof Error ? error.stack : undefined,
status: ResponseStatus.FAILURE,
} satisfies ResponsePayload
return { status: ResponseStatus.SUCCESS }
} catch (error) {
return {
- errorMessage: error instanceof Error ? error.message : String(error),
+ errorMessage: getErrorMessage(error),
errorStack: error instanceof Error ? error.stack : undefined,
status: ResponseStatus.FAILURE,
} satisfies ResponsePayload
return { status: ResponseStatus.SUCCESS }
} catch (error) {
return {
- errorMessage: error instanceof Error ? error.message : String(error),
+ errorMessage: getErrorMessage(error),
errorStack: error instanceof Error ? error.stack : undefined,
status: ResponseStatus.FAILURE,
} satisfies ResponsePayload
import { BaseError } from '../../exception/index.js'
import { FileType, MapStringifyFormat, type Statistics } from '../../types/index.js'
-import { AsyncLock, AsyncLockType, handleFileException, JSONStringify } from '../../utils/index.js'
+import {
+ AsyncLock,
+ AsyncLockType,
+ ensureError,
+ handleFileException,
+ JSONStringify,
+} from '../../utils/index.js'
import { Storage } from './Storage.js'
export class JsonFileStorage extends Storage {
handleFileException(
this.dbName,
FileType.PerformanceRecords,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
this.logPrefix
)
}
handleFileException(
this.dbName,
FileType.PerformanceRecords,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
this.logPrefix
)
}
handleFileException(
this.dbName,
FileType.PerformanceRecords,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
this.logPrefix
)
})
import { BaseError } from '../../exception/index.js'
import { PerformanceRecord, type Statistics, StorageType } from '../../types/index.js'
-import { Constants } from '../../utils/index.js'
+import { Constants, ensureError } from '../../utils/index.js'
import { Storage } from './Storage.js'
export class MikroOrmStorage extends Storage {
delete this.orm
}
} catch (error) {
- this.handleDBStorageError(
- this.storageType,
- error instanceof Error ? error : new Error(String(error))
- )
+ this.handleDBStorageError(this.storageType, ensureError(error))
}
}
}
}
} catch (error) {
- this.handleDBStorageError(
- this.storageType,
- error instanceof Error ? error : new Error(String(error))
- )
+ this.handleDBStorageError(this.storageType, ensureError(error))
}
}
} catch (error) {
this.handleDBStorageError(
this.storageType,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
Constants.PERFORMANCE_RECORDS_TABLE
)
}
import { BaseError } from '../../exception/index.js'
import { type Statistics, StorageType } from '../../types/index.js'
-import { Constants } from '../../utils/index.js'
+import { Constants, ensureError } from '../../utils/index.js'
import { Storage } from './Storage.js'
export class MongoDBStorage extends Storage {
this.opened = false
}
} catch (error) {
- this.handleDBStorageError(
- StorageType.MONGO_DB,
- error instanceof Error ? error : new Error(String(error))
- )
+ this.handleDBStorageError(StorageType.MONGO_DB, ensureError(error))
}
}
this.opened = true
}
} catch (error) {
- this.handleDBStorageError(
- StorageType.MONGO_DB,
- error instanceof Error ? error : new Error(String(error))
- )
+ this.handleDBStorageError(StorageType.MONGO_DB, ensureError(error))
}
}
} catch (error) {
this.handleDBStorageError(
StorageType.MONGO_DB,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
Constants.PERFORMANCE_RECORDS_TABLE
)
}
logPrefix,
} from './ConfigurationUtils.js'
import { Constants } from './Constants.js'
-import { handleFileException } from './ErrorUtils.js'
+import { ensureError, handleFileException } from './ErrorUtils.js'
import { has, isCFEnvironment, mergeDeepRight, once } from './Utils.js'
type ConfigurationSectionType =
handleFileException(
Configuration.configurationFile,
FileType.Configuration,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
logPrefix(),
{ consoleOut: true }
)
handleFileException(
Configuration.configurationFile,
FileType.Configuration,
- error instanceof Error ? error : new Error(String(error)),
+ ensureError(error),
logPrefix(),
{ consoleOut: true }
)
const moduleName = 'ErrorUtils'
+export const ensureError = (error: unknown): Error =>
+ error instanceof Error ? error : new Error(String(error))
+
+export const getErrorMessage = (error: unknown): string =>
+ error instanceof Error ? error.message : String(error)
+
export const handleUncaughtException = (): void => {
process.on('uncaughtException', (error: Error) => {
console.error(chalk.red('Uncaught exception: '), error)
import type { FileType } from '../types/index.js'
-import { handleFileException } from './ErrorUtils.js'
+import { ensureError, handleFileException } from './ErrorUtils.js'
import { logger } from './Logger.js'
import { isNotEmptyString } from './Utils.js'
try {
return watch(file, listener)
} catch (error) {
- handleFileException(
- file,
- fileType,
- error instanceof Error ? error : new Error(String(error)),
- logPrefix,
- {
- throwError: false,
- }
- )
+ handleFileException(file, fileType, ensureError(error), logPrefix, {
+ throwError: false,
+ })
}
} else {
logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`)
export { Constants } from './Constants.js'
export { ACElectricUtils, DCElectricUtils } from './ElectricUtils.js'
export {
+ ensureError,
+ getErrorMessage,
handleFileException,
handleIncomingRequestError,
handleSendMessageError,