-
Notifications
You must be signed in to change notification settings - Fork 1
/
throwOnConsole.ts
84 lines (72 loc) · 2.14 KB
/
throwOnConsole.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Instead of 'node:util' because it doesn't work in the browser
import { format } from './util';
type Options = {
/**
* Messages to ignore (won't throw), each message to ignore can be a substring or a regex.
*
* Empty list by default.
*/
ignore?: (string | RegExp)[];
};
type ConsoleMethodName = 'assert' | 'error' | 'warn' | 'info' | 'log' | 'dir' | 'debug';
function formatMessage(ignore: Options['ignore'], ...data: any[]) {
ignore = ignore ?? [];
const message = format(...data);
return {
shouldThrow: !ignore.some(msgToIgnore =>
typeof msgToIgnore === 'string' ? message.includes(msgToIgnore) : message.match(msgToIgnore)
),
message
};
}
const originalConsole = {
assert: console.assert,
error: console.error,
warn: console.warn,
info: console.info,
log: console.log,
dir: console.dir,
debug: console.debug
};
export class ThrowOnError extends Error {
constructor(message: string) {
super(message);
this.name = 'ThrowOnError';
// No stack trace
this.stack = undefined;
}
}
function getFirstLine(message: string) {
const lines = message.split('\n');
return lines.length > 1 ? lines[0] : message;
}
/**
* Makes console method to throw if called.
*/
export function throwOnConsole(methodName: ConsoleMethodName, options: Options = {}) {
const { ignore } = options;
if (methodName === 'assert') {
console.assert = (condition?: boolean, ...data: any[]) => {
if (!condition) {
const { shouldThrow, message } = formatMessage(ignore, ...data);
if (shouldThrow) {
throw new ThrowOnError(`throw-on console.assert: ${getFirstLine(message)}`);
}
}
};
} else {
console[methodName] = (...data: any[]) => {
originalConsole[methodName](...data);
const { shouldThrow, message } = formatMessage(ignore, ...data);
if (shouldThrow) {
throw new ThrowOnError(`throw-on console.${methodName}: ${getFirstLine(message)}`);
}
};
}
}
/**
* Restores the original console method implementation.
*/
export function restoreConsole(methodName: ConsoleMethodName) {
console[methodName] = originalConsole[methodName];
}