1 import chalk from
'chalk';
3 import { logger
} from
'./Logger';
4 import { Utils
} from
'./Utils';
5 import type { ChargingStation
} from
'../charging-station';
10 IncomingRequestCommand
,
15 const defaultErrorParams
= {
20 export class ErrorUtils
{
21 private constructor() {
22 // This is intentional
25 public static handleUncaughtException(): void {
26 process
.on('uncaughtException', (error
: Error) => {
27 console
.error(chalk
.red('Uncaught exception: '), error
);
31 public static handleUnhandledRejection(): void {
32 process
.on('unhandledRejection', (reason
: unknown
) => {
33 console
.error(chalk
.red('Unhandled rejection: '), reason
);
37 public static handleFileException(
40 error
: NodeJS
.ErrnoException
,
42 params
: HandleErrorParams
<EmptyObject
> = defaultErrorParams
44 ErrorUtils
.setDefaultErrorParams(params
);
45 const prefix
= Utils
.isNotEmptyString(logPrefix
) ? `${logPrefix} ` : '';
49 logMsg
= `${fileType} file ${file} not found:`;
52 logMsg
= `${fileType} file ${file} already exists:`;
55 logMsg
= `${fileType} file ${file} access denied:`;
58 logMsg
= `${fileType} file ${file} permission denied:`;
61 logMsg
= `${fileType} file ${file} error:`;
63 if (params
?.consoleOut
=== true) {
64 if (params
?.throwError
) {
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
) {
71 logger
.error(`${prefix}${logMsg}`, error
);
73 logger
.warn(`${prefix}${logMsg}`, error
);
76 if (params
?.throwError
) {
81 public static handleSendMessageError(
82 chargingStation
: ChargingStation
,
83 commandName
: RequestCommand
| IncomingRequestCommand
,
85 params
: HandleErrorParams
<EmptyObject
> = { throwError
: false, consoleOut
: false }
87 ErrorUtils
.setDefaultErrorParams(params
, { throwError
: false, consoleOut
: false });
88 logger
.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error
);
89 if (params
?.throwError
=== true) {
94 public static setDefaultErrorParams
<T
extends JsonType
>(
95 params
: HandleErrorParams
<T
>,
96 defaultParams
: HandleErrorParams
<T
> = defaultErrorParams
97 ): HandleErrorParams
<T
> {
98 return { ...defaultParams
, ...params
};