1fd0482bd78b1bd9996961b8c07c8a359f3c2982
[e-mobility-charging-stations-simulator.git] / src / utils / ErrorUtils.ts
1 import process from 'node:process'
2
3 import chalk from 'chalk'
4
5 import { logger } from './Logger.js'
6 import { isNotEmptyString } from './Utils.js'
7 import type { ChargingStation } from '../charging-station/index.js'
8 import type {
9 EmptyObject,
10 FileType,
11 HandleErrorParams,
12 IncomingRequestCommand,
13 JsonType,
14 RequestCommand
15 } from '../types/index.js'
16
17 const defaultErrorParams = {
18 throwError: true,
19 consoleOut: false
20 }
21
22 export const handleUncaughtException = (): void => {
23 process.on('uncaughtException', (error: Error) => {
24 console.error(chalk.red('Uncaught exception: '), error)
25 })
26 }
27
28 export const handleUnhandledRejection = (): void => {
29 process.on('unhandledRejection', (reason: unknown) => {
30 console.error(chalk.red('Unhandled rejection: '), reason)
31 })
32 }
33
34 export const handleFileException = (
35 file: string,
36 fileType: FileType,
37 error: NodeJS.ErrnoException,
38 logPrefix: string,
39 params: HandleErrorParams<EmptyObject> = defaultErrorParams
40 ): void => {
41 setDefaultErrorParams(params)
42 const prefix = isNotEmptyString(logPrefix) ? `${logPrefix} ` : ''
43 let logMsg: string
44 switch (error.code) {
45 case 'ENOENT':
46 logMsg = `${fileType} file ${file} not found:`
47 break
48 case 'EEXIST':
49 logMsg = `${fileType} file ${file} already exists:`
50 break
51 case 'EACCES':
52 logMsg = `${fileType} file ${file} access denied:`
53 break
54 case 'EPERM':
55 logMsg = `${fileType} file ${file} permission denied:`
56 break
57 default:
58 logMsg = `${fileType} file ${file} error:`
59 }
60 if (params?.consoleOut === true) {
61 logMsg = `${logMsg} `
62 if (params?.throwError === true) {
63 console.error(`${chalk.green(prefix)}${chalk.red(logMsg)}`, error)
64 } else {
65 console.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error)
66 }
67 } else if (params?.consoleOut === false) {
68 if (params?.throwError === true) {
69 logger.error(`${prefix}${logMsg}`, error)
70 } else {
71 logger.warn(`${prefix}${logMsg}`, error)
72 }
73 }
74 if (params?.throwError === true) {
75 throw error
76 }
77 }
78
79 export const handleSendMessageError = (
80 chargingStation: ChargingStation,
81 commandName: RequestCommand | IncomingRequestCommand,
82 error: Error,
83 params: HandleErrorParams<EmptyObject> = { throwError: false, consoleOut: false }
84 ): void => {
85 setDefaultErrorParams(params, { throwError: false, consoleOut: false })
86 logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error)
87 if (params?.throwError === true) {
88 throw error
89 }
90 }
91
92 export const setDefaultErrorParams = <T extends JsonType>(
93 params: HandleErrorParams<T>,
94 defaultParams: HandleErrorParams<T> = defaultErrorParams
95 ): HandleErrorParams<T> => {
96 params = { ...defaultParams, ...params }
97 return params
98 }