Skip to content

Commit 3ef4317

Browse files
committed
console made colorful using ansi escape codes
1 parent 35a9499 commit 3ef4317

File tree

1 file changed

+47
-7
lines changed

1 file changed

+47
-7
lines changed

src/global-error-handler.ts

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,34 @@ import { StatusCodes, getStatusMessage } from 'http-status-toolkit';
33
import { isCustomAPIError } from './checking-custom-api-error';
44
import { CustomAPIError } from './error';
55

6+
const colors = {
7+
reset: '\x1b[0m',
8+
bold: '\x1b[1m',
9+
red: '\x1b[31m',
10+
yellow: '\x1b[33m',
11+
green: '\x1b[32m',
12+
};
613

14+
function boldRed(text: string) {
15+
return `${colors.bold}${colors.red}${text}${colors.reset}`;
16+
}
17+
function red(text: string) {
18+
return `${colors.red}${text}${colors.reset}`;
19+
}
20+
21+
function boldYellow(text: string) {
22+
return `${colors.bold}${colors.yellow}${text}${colors.reset}`;
23+
}
24+
function yellow(text: string) {
25+
return `${colors.yellow}${text}${colors.reset}`;
26+
}
27+
28+
function boldGreen(text: string) {
29+
return `${colors.bold}${colors.green}${text}${colors.reset}`;
30+
}
31+
function green(text: string) {
32+
return `${colors.green}${text}${colors.reset}`;
33+
}
734

835
// Internal config object (optional override)
936
let errorOptions = {
@@ -68,13 +95,26 @@ export const globalErrorHandler = (
6895

6996
// Log the error if configured to do so
7097
if (errorOptions.logError) {
71-
console.error('\x1b[35m%s\x1b[31m', 'Error Message:', errorResponse.message);
72-
if (errorResponse.errorDetails) {
73-
console.error('Error Details:', errorResponse.errorDetails);
74-
}
75-
if (errorResponse.stack) {
76-
console.error('\x1b[35m%s\x1b[32m', 'Stack Trace:', errorResponse.stack);
77-
}
98+
console.error(boldRed('🔴 Error Message:'));
99+
console.error(red(errorResponse.message));
100+
101+
if (errorResponse.errorDetails) {
102+
console.error(boldYellow('🟡 Error Details:'));
103+
console.error(
104+
yellow(
105+
typeof errorResponse.errorDetails === 'object'
106+
? JSON.stringify(errorResponse.errorDetails, null, 2)
107+
: errorResponse.errorDetails
108+
)
109+
);
110+
}
111+
112+
if (errorResponse.stack) {
113+
console.error(boldGreen('🟢 Stack Trace:'));
114+
(errorResponse.stack as string[]).forEach((line) =>
115+
console.error(green(line))
116+
);
117+
}
78118
}
79119

80120
res.status(statusCode).json(errorResponse);

0 commit comments

Comments
 (0)