Initial code cleanups for the future OCPP requests code optimization
[e-mobility-charging-stations-simulator.git] / src / utils / FileUtils.ts
CommitLineData
717c1e56 1import { EmptyObject } from '../types/EmptyObject';
e0a50bcd 2import { HandleErrorParams } from '../types/Error';
e8191622 3import Utils from './Utils';
8eac9a09 4import chalk from 'chalk';
9f2e3130 5import logger from './Logger';
23132a44
JB
6
7export default class FileUtils {
e7aeea18
JB
8 static handleFileException(
9 logPrefix: string,
10 fileType: string,
11 filePath: string,
12 error: NodeJS.ErrnoException,
13 params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false }
14 ): void {
e8191622 15 const prefix = !Utils.isEmptyString(logPrefix) ? logPrefix + ' ' : '';
23132a44 16 if (error.code === 'ENOENT') {
e0a50bcd 17 if (params?.consoleOut) {
e7aeea18
JB
18 console.warn(
19 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + filePath + ' not found: '),
20 error
21 );
23132a44 22 } else {
9f2e3130 23 logger.warn(prefix + fileType + ' file ' + filePath + ' not found: %j', error);
23132a44 24 }
72f041bd 25 } else if (error.code === 'EEXIST') {
e0a50bcd 26 if (params?.consoleOut) {
e7aeea18
JB
27 console.warn(
28 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + filePath + ' already exists: '),
29 error
30 );
72f041bd 31 } else {
9f2e3130 32 logger.warn(prefix + fileType + ' file ' + filePath + ' already exists: %j', error);
72f041bd
JB
33 }
34 } else if (error.code === 'EACCES') {
e0a50bcd 35 if (params?.consoleOut) {
e7aeea18
JB
36 console.warn(
37 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + filePath + ' access denied: '),
38 error
39 );
72f041bd 40 } else {
9f2e3130 41 logger.warn(prefix + fileType + ' file ' + filePath + ' access denied: %j', error);
72f041bd 42 }
23132a44 43 } else {
e0a50bcd 44 if (params?.consoleOut) {
e7aeea18
JB
45 console.warn(
46 chalk.green(prefix) + chalk.yellow(fileType + ' file ' + filePath + ' error: '),
47 error
48 );
23132a44 49 } else {
9f2e3130 50 logger.warn(prefix + fileType + ' file ' + filePath + ' error: %j', error);
23132a44 51 }
e0a50bcd
JB
52 if (params?.throwError) {
53 throw error;
54 }
23132a44
JB
55 }
56 }
57}