Fix incoming message error handling
[e-mobility-charging-stations-simulator.git] / src / utils / FileUtils.ts
CommitLineData
717c1e56 1import { EmptyObject } from '../types/EmptyObject';
e0a50bcd 2import { HandleErrorParams } from '../types/Error';
8eac9a09 3import chalk from 'chalk';
9f2e3130 4import logger from './Logger';
23132a44
JB
5
6export default class FileUtils {
e0a50bcd 7 static handleFileException(logPrefix: string, fileType: string, filePath: string, error: NodeJS.ErrnoException,
717c1e56 8 params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false }): void {
23132a44
JB
9 const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
10 if (error.code === 'ENOENT') {
e0a50bcd 11 if (params?.consoleOut) {
e4362ed7 12 console.warn(chalk.green(prefix) + chalk.yellow(fileType + ' file ' + filePath + ' not found: '), error);
23132a44 13 } else {
9f2e3130 14 logger.warn(prefix + fileType + ' file ' + filePath + ' not found: %j', error);
23132a44 15 }
72f041bd 16 } else if (error.code === 'EEXIST') {
e0a50bcd 17 if (params?.consoleOut) {
e4362ed7 18 console.warn(chalk.green(prefix) + chalk.yellow(fileType + ' file ' + filePath + ' already exists: '), error);
72f041bd 19 } else {
9f2e3130 20 logger.warn(prefix + fileType + ' file ' + filePath + ' already exists: %j', error);
72f041bd
JB
21 }
22 } else if (error.code === 'EACCES') {
e0a50bcd 23 if (params?.consoleOut) {
e4362ed7 24 console.warn(chalk.green(prefix) + chalk.yellow(fileType + ' file ' + filePath + ' access denied: '), error);
72f041bd 25 } else {
9f2e3130 26 logger.warn(prefix + fileType + ' file ' + filePath + ' access denied: %j', error);
72f041bd 27 }
23132a44 28 } else {
e0a50bcd 29 if (params?.consoleOut) {
e4362ed7 30 console.warn(chalk.green(prefix) + chalk.yellow(fileType + ' file ' + filePath + ' error: '), error);
23132a44 31 } else {
9f2e3130 32 logger.warn(prefix + fileType + ' file ' + filePath + ' error: %j', error);
23132a44 33 }
e0a50bcd
JB
34 if (params?.throwError) {
35 throw error;
36 }
23132a44
JB
37 }
38 }
39}