"evses",
"iccid",
"idtag",
+ "idtags",
"imsi",
"lcov",
"logform",
private getConfigurationFromFile(): ChargingStationConfiguration | undefined {
let configuration: ChargingStationConfiguration | undefined;
- if (this.configurationFile && fs.existsSync(this.configurationFile)) {
+ if (Utils.isNotEmptyString(this.configurationFile) && fs.existsSync(this.configurationFile)) {
try {
if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
configuration = this.sharedLRUCache.getChargingStationConfiguration(
private saveConfiguration(
chargingStationAutomaticTransactionGeneratorConfiguration?: ChargingStationAutomaticTransactionGeneratorConfiguration
): void {
- if (this.configurationFile) {
+ if (Utils.isNotEmptyString(this.configurationFile)) {
try {
if (!fs.existsSync(path.dirname(this.configurationFile))) {
fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
key: ConfigurationKeyType,
params: DeleteConfigurationKeyParams = { save: true, caseInsensitive: false }
): ConfigurationKey[] | undefined {
+ params = { ...{ save: true, caseInsensitive: false }, ...params };
const keyFound = ChargingStationConfigurationUtils.getConfigurationKey(
chargingStation,
key,
return IdTagsCache.instance;
}
+ /**
+ * Get one idtag from the cache given the distribution
+ * Must be called after checking the cache is not an empty array
+ *
+ * @param distribution
+ * @param chargingStation
+ * @param connectorId
+ * @returns
+ */
public getIdTag(
distribution: IdTagDistribution,
chargingStation: ChargingStation,
}
}
+ /**
+ * Get all idtags from the cache
+ * Must be called after checking the cache is not an empty array
+ *
+ * @param file
+ * @returns
+ */
public getIdTags(file: string): string[] | undefined {
if (this.hasIdTagsCache(file) === false) {
- this.setIdTagsCache(file, this.getIdTagsFromFile(file));
+ this.setIdTagsCache(
+ Utils.isNotEmptyString(file) ? file : 'empty',
+ this.getIdTagsFromFile(file)
+ );
}
return this.getIdTagsCache(file);
}
}
private getIdTagsFromFile(file: string): string[] {
- let idTags: string[] = [];
- if (file) {
+ if (Utils.isNotEmptyString(file)) {
try {
- // Load id tags file
- idTags = JSON.parse(fs.readFileSync(file, 'utf8')) as string[];
+ return JSON.parse(fs.readFileSync(file, 'utf8')) as string[];
} catch (error) {
ErrorUtils.handleFileException(
file,
this.logPrefix(file)
);
}
- } else {
- logger.info(`${this.logPrefix(file)} No id tags file given`);
}
- return idTags;
+ logger.info(`${this.logPrefix(file)} No id tags file given in configuration`);
+ return [];
}
private logPrefix = (file: string): string => {
JsonType,
OCPPVersion,
} from '../../types';
-import { logger } from '../../utils';
+import { ErrorUtils, logger } from '../../utils';
const moduleName = 'OCPPIncomingRequestService';
return OCPPIncomingRequestService.instance as T;
}
- protected handleIncomingRequestError<T>(
+ protected handleIncomingRequestError<T extends JsonType>(
chargingStation: ChargingStation,
commandName: IncomingRequestCommand,
error: Error,
- params: HandleErrorParams<T> = { throwError: true }
+ params: HandleErrorParams<T> = { throwError: true, consoleOut: false }
): T | undefined {
+ ErrorUtils.handleErrorParams(params);
logger.error(
`${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
error
throwError: false,
}
): Promise<ResponseType> {
+ params = {
+ ...{ skipBufferingOnError: false, triggerMessage: false, throwError: false },
+ ...params,
+ };
try {
return await this.internalSendMessage(
chargingStation,
params: RequestParams = {
skipBufferingOnError: false,
triggerMessage: false,
+ throwError: false,
}
): Promise<ResponseType> {
+ params = {
+ ...{ skipBufferingOnError: false, triggerMessage: false, throwError: false },
+ ...params,
+ };
if (
(chargingStation.inUnknownState() === true &&
commandName === RequestCommand.BOOT_NOTIFICATION) ||
import type { AbstractUIService } from './ui-services/AbstractUIService';
import { UIServiceFactory } from './ui-services/UIServiceFactory';
+import { BaseError } from '../../exception';
import {
AuthenticationType,
type ChargingStationData,
protected authenticate(req: IncomingMessage, next: (err?: Error) => void): void {
if (this.isBasicAuthEnabled() === true) {
if (this.isValidBasicAuth(req) === false) {
- next(new Error('Unauthorized'));
+ next(new BaseError('Unauthorized'));
}
next();
}
import path from 'node:path';
import { Storage } from './Storage';
+import { BaseError } from '../../exception';
import { FileType, type Statistics } from '../../types';
import { AsyncLock, AsyncLockType, Constants, ErrorUtils, Utils } from '../../utils';
private checkPerformanceRecordsFile(): void {
if (!this?.fd) {
- throw new Error(
+ throw new BaseError(
`${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
);
}
import { MongoClient } from 'mongodb';
import { Storage } from './Storage';
+import { BaseError } from '../../exception';
import { type Statistics, StorageType } from '../../types';
import { Constants } from '../../utils';
private checkDBConnection() {
if (!this?.client) {
- throw new Error(
+ throw new BaseError(
`${this.logPrefix} ${this.getDBNameFromStorageType(
StorageType.MONGO_DB
)} client initialization failed while trying to issue a request`
);
}
if (!this.connected) {
- throw new Error(
+ throw new BaseError(
`${this.logPrefix} ${this.getDBNameFromStorageType(
StorageType.MONGO_DB
)} connection not opened while trying to issue a request`
type Statistics,
StorageType,
} from '../../types';
-import { Utils, logger } from '../../utils';
+import { ErrorUtils, Utils, logger } from '../../utils';
export abstract class Storage {
protected readonly storageUri: URL;
type: StorageType,
error: Error,
table?: string,
- params: HandleErrorParams<EmptyObject> = { throwError: false }
+ params: HandleErrorParams<EmptyObject> = { throwError: false, consoleOut: false }
): void {
+ ErrorUtils.handleErrorParams(params, { throwError: false, consoleOut: false });
const inTableOrCollectionStr =
(!Utils.isNullOrUndefined(table) || !table) && ` in table or collection '${table}'`;
logger.error(
import { MikroOrmStorage } from './MikroOrmStorage';
import { MongoDBStorage } from './MongoDBStorage';
import type { Storage } from './Storage';
+import { BaseError } from '../../exception';
import { StorageType } from '../../types';
export class StorageFactory {
// storageInstance = new MikroOrmStorage(connectionUri, logPrefix, type);
// break;
default:
- throw new Error(`${logPrefix} Unknown storage type: ${type}`);
+ throw new BaseError(`${logPrefix} Unknown storage type: ${type}`);
}
return storageInstance;
}
-export type HandleErrorParams<T> = {
+import type { JsonType } from './JsonType';
+
+export type HandleErrorParams<T extends JsonType> = {
throwError?: boolean;
consoleOut?: boolean;
errorResponse?: T;
case 'EACCES':
logMsg = `${fileType} file ${file} access denied:`;
break;
+ case 'EPERM':
+ logMsg = `${fileType} file ${file} permission denied:`;
+ break;
default:
logMsg = `${fileType} file ${file} error:`;
}
- console.warn(`${chalk.green(prefix)}${chalk.yellow(`${logMsg} `)}`, error);
+ console.error(`${chalk.green(prefix)}${chalk.red(`${logMsg} `)}`, error);
+ throw error;
}
private static getDefaultPerformanceStorageUri(storageType: StorageType) {
FileType,
HandleErrorParams,
IncomingRequestCommand,
+ JsonType,
RequestCommand,
} from '../types';
logPrefix: string,
params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false }
): void {
+ ErrorUtils.handleErrorParams(params);
const prefix = Utils.isNotEmptyString(logPrefix) ? `${logPrefix} ` : '';
let logMsg: string;
switch (error.code) {
case 'EACCES':
logMsg = `${fileType} file ${file} access denied:`;
break;
+ case 'EPERM':
+ logMsg = `${fileType} file ${file} permission denied:`;
+ break;
default:
logMsg = `${fileType} file ${file} error:`;
}
- if (params?.consoleOut) {
- console.warn(`${chalk.green(prefix)}${chalk.yellow(`${logMsg} `)}`, error);
- } else {
- logger.warn(`${prefix}${logMsg}`, error);
+ if (params?.consoleOut === true) {
+ if (params?.throwError) {
+ console.error(`${chalk.green(prefix)}${chalk.red(`${logMsg} `)}`, error);
+ } else {
+ console.warn(`${chalk.green(prefix)}${chalk.yellow(`${logMsg} `)}`, error);
+ }
+ } else if (params?.consoleOut === false) {
+ if (params?.throwError) {
+ logger.error(`${prefix}${logMsg}`, error);
+ } else {
+ logger.warn(`${prefix}${logMsg}`, error);
+ }
}
if (params?.throwError) {
throw error;
chargingStation: ChargingStation,
commandName: RequestCommand | IncomingRequestCommand,
error: Error,
- params: HandleErrorParams<EmptyObject> = { throwError: false }
+ params: HandleErrorParams<EmptyObject> = { throwError: false, consoleOut: false }
): void {
+ ErrorUtils.handleErrorParams(params, { throwError: false, consoleOut: false });
logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
if (params?.throwError === true) {
throw error;
}
}
+
+ public static handleErrorParams<T extends JsonType>(
+ params: HandleErrorParams<T>,
+ defaultParams: HandleErrorParams<T> = { throwError: true, consoleOut: false }
+ ): HandleErrorParams<T> {
+ return { ...defaultParams, ...params };
+ }
}