1 import chalk from
'chalk'
2 import process from
'node:process'
4 import type { ChargingStation
} from
'../charging-station/index.js'
9 IncomingRequestCommand
,
13 } from
'../types/index.js'
15 import { getMessageTypeString
} from
'../charging-station/ocpp/OCPPServiceUtils.js'
16 import { logger
} from
'./Logger.js'
17 import { isNotEmptyString
} from
'./Utils.js'
19 const moduleName
= 'ErrorUtils'
21 export const handleUncaughtException
= (): void => {
22 process
.on('uncaughtException', (error
: Error) => {
23 console
.error(chalk
.red('Uncaught exception: '), error
)
27 export const handleUnhandledRejection
= (): void => {
28 process
.on('unhandledRejection', (reason
: unknown
) => {
29 console
.error(chalk
.red('Unhandled rejection: '), reason
)
33 export const handleFileException
= (
36 error
: NodeJS
.ErrnoException
,
38 params
?: HandleErrorParams
<EmptyObject
>
47 const prefix
= isNotEmptyString(logPrefix
) ? `${logPrefix} ` : ''
51 logMsg
= `${fileType} file ${file} not found:`
54 logMsg
= `${fileType} file ${file} already exists:`
57 logMsg
= `${fileType} file ${file} access denied:`
60 logMsg
= `${fileType} file ${file} permission denied:`
63 logMsg
= `${fileType} file ${file} error:`
65 if (params
.consoleOut
=== true) {
67 if (params
.throwError
=== true) {
68 console
.error(`${chalk.green(prefix)}${chalk.red(logMsg)}`, error
)
70 console
.warn(`${chalk.green(prefix)}${chalk.yellow(logMsg)}`, error
)
72 } else if (params
.consoleOut
=== false) {
73 if (params
.throwError
=== true) {
74 logger
.error(`${prefix}${logMsg}`, error
)
76 logger
.warn(`${prefix}${logMsg}`, error
)
79 if (params
.throwError
=== true) {
84 export const handleSendMessageError
= (
85 chargingStation
: ChargingStation
,
86 commandName
: IncomingRequestCommand
| RequestCommand
,
87 messageType
: MessageType
,
89 params
?: HandleErrorParams
<EmptyObject
>
99 `${chargingStation.logPrefix()} ${moduleName}.handleSendMessageError: Send ${getMessageTypeString(messageType)} command '${commandName}' error:`,
102 if (params
.throwError
=== true) {
107 export const handleIncomingRequestError
= <T
extends JsonType
>(
108 chargingStation
: ChargingStation
,
109 commandName
: IncomingRequestCommand
,
111 params
?: HandleErrorParams
<T
>
112 ): T
| undefined => {
121 `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
124 if (params
.throwError
=== false && params
.errorResponse
!= null) {
125 return params
.errorResponse
127 if (params
.throwError
=== true && params
.errorResponse
== null) {
130 if (params
.throwError
=== true && params
.errorResponse
!= null) {
131 return params
.errorResponse