1 import process from
'node:process'
3 import chalk from
'chalk'
5 import type { ChargingStation
} from
'../charging-station/index.js'
6 import { getMessageTypeString
} from
'../charging-station/ocpp/OCPPServiceUtils.js'
11 IncomingRequestCommand
,
15 } from
'../types/index.js'
16 import { logger
} from
'./Logger.js'
17 import { isNotEmptyString
} from
'./Utils.js'
19 const defaultErrorParams
= {
22 } satisfies HandleErrorParams
<EmptyObject
>
24 export const handleUncaughtException
= (): void => {
25 process
.on('uncaughtException', (error
: Error) => {
26 console
.error(chalk
.red('Uncaught exception: '), error
)
30 export const handleUnhandledRejection
= (): void => {
31 process
.on('unhandledRejection', (reason
: unknown
) => {
32 console
.error(chalk
.red('Unhandled rejection: '), reason
)
36 export const handleFileException
= (
39 error
: NodeJS
.ErrnoException
,
41 params
: HandleErrorParams
<EmptyObject
> = defaultErrorParams
43 params
= setDefaultErrorParams(params
)
44 const prefix
= isNotEmptyString(logPrefix
) ? `${logPrefix} ` : ''
48 logMsg
= `${fileType} file ${file} not found:`
51 logMsg
= `${fileType} file ${file} already exists:`
54 logMsg
= `${fileType} file ${file} access denied:`
57 logMsg
= `${fileType} file ${file} permission denied:`
60 logMsg
= `${fileType} file ${file} error:`
62 if (params
.consoleOut
=== true) {
64 if (params
.throwError
=== true) {
65 console
.error(`${chalk.green(prefix)}${chalk.red(logMsg)}`, error
)
67 console
.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error
)
69 } else if (params
.consoleOut
=== false) {
70 if (params
.throwError
=== true) {
71 logger
.error(`${prefix}${logMsg}`, error
)
73 logger
.warn(`${prefix}${logMsg}`, error
)
76 if (params
.throwError
=== true) {
81 export const handleSendMessageError
= (
82 chargingStation
: ChargingStation
,
83 commandName
: RequestCommand
| IncomingRequestCommand
,
84 messageType
: MessageType
,
86 params
: HandleErrorParams
<EmptyObject
> = {
91 params
= setDefaultErrorParams(params
, { throwError
: false, consoleOut
: false })
93 `${chargingStation.logPrefix()} Send ${getMessageTypeString(messageType)} command '${commandName}' error:`,
96 if (params
.throwError
=== true) {
101 export const setDefaultErrorParams
= <T
extends JsonType
>(
102 params
: HandleErrorParams
<T
>,
103 defaultParams
: HandleErrorParams
<T
> = defaultErrorParams
104 ): HandleErrorParams
<T
> => {
105 return { ...defaultParams
, ...params
}