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