| 1 | import chalk from 'chalk'; |
| 2 | |
| 3 | import { logger } from './Logger'; |
| 4 | import { Utils } from './Utils'; |
| 5 | import type { ChargingStation } from '../charging-station'; |
| 6 | import type { |
| 7 | EmptyObject, |
| 8 | FileType, |
| 9 | HandleErrorParams, |
| 10 | IncomingRequestCommand, |
| 11 | RequestCommand, |
| 12 | } from '../types'; |
| 13 | |
| 14 | export class ErrorUtils { |
| 15 | private constructor() { |
| 16 | // This is intentional |
| 17 | } |
| 18 | |
| 19 | public static handleUncaughtException(): void { |
| 20 | process.on('uncaughtException', (error: Error) => { |
| 21 | console.error(chalk.red('Uncaught exception: '), error); |
| 22 | }); |
| 23 | } |
| 24 | |
| 25 | public static handleUnhandledRejection(): void { |
| 26 | process.on('unhandledRejection', (reason: unknown) => { |
| 27 | console.error(chalk.red('Unhandled rejection: '), reason); |
| 28 | }); |
| 29 | } |
| 30 | |
| 31 | public static handleFileException( |
| 32 | file: string, |
| 33 | fileType: FileType, |
| 34 | error: NodeJS.ErrnoException, |
| 35 | logPrefix: string, |
| 36 | params: HandleErrorParams<EmptyObject> = { throwError: true, consoleOut: false } |
| 37 | ): void { |
| 38 | const prefix = Utils.isNotEmptyString(logPrefix) ? `${logPrefix} ` : ''; |
| 39 | let logMsg: string; |
| 40 | switch (error.code) { |
| 41 | case 'ENOENT': |
| 42 | logMsg = `${fileType} file ${file} not found:`; |
| 43 | break; |
| 44 | case 'EEXIST': |
| 45 | logMsg = `${fileType} file ${file} already exists:`; |
| 46 | break; |
| 47 | case 'EACCES': |
| 48 | logMsg = `${fileType} file ${file} access denied:`; |
| 49 | break; |
| 50 | default: |
| 51 | logMsg = `${fileType} file ${file} error:`; |
| 52 | } |
| 53 | if (params?.consoleOut) { |
| 54 | console.warn(`${chalk.green(prefix)}${chalk.yellow(`${logMsg} `)}`, error); |
| 55 | } else { |
| 56 | logger.warn(`${prefix}${logMsg}`, error); |
| 57 | } |
| 58 | if (params?.throwError) { |
| 59 | throw error; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | public static handleSendMessageError( |
| 64 | chargingStation: ChargingStation, |
| 65 | commandName: RequestCommand | IncomingRequestCommand, |
| 66 | error: Error, |
| 67 | params: HandleErrorParams<EmptyObject> = { throwError: false } |
| 68 | ): void { |
| 69 | logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error); |
| 70 | if (params?.throwError === true) { |
| 71 | throw error; |
| 72 | } |
| 73 | } |
| 74 | } |