-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
63 lines (58 loc) · 1.45 KB
/
main.ts
File metadata and controls
63 lines (58 loc) · 1.45 KB
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
/**
* Check if a value is an `Error` instance.
*
* This is like `value instanceof Error` except it works across realms, such as
* iframes or Node.js [`vm`](https://nodejs.org/api/vm.html).
*
* @example
* ```js
* isErrorInstance(new Error('')) // true
* isErrorInstance('') // false
*
* const CrossRealmError = vm.runInNewContext('Error')
* isErrorInstance(new CrossRealmError('')) // true
*
* isErrorInstance(new TypeError('')) // true
* isErrorInstance(new AnyOtherError('')) // true
*
* isErrorInstance(new DOMException('')) // true
* isErrorInstance(new DOMError('')) // true
*
* isErrorInstance(new Proxy(new Error(''), {})) // true
* isErrorInstance(
* new Proxy(new Error(''), {
* getPrototypeOf() {
* throw new Error('')
* },
* }),
* ) // false
* ```
*/
const isErrorInstance = <T>(value: T) =>
(isInstanceOfError(value) || hasErrorTag(value)) as ErrorCheck<T>
export default isErrorInstance
type ErrorCheck<T> = T extends Error ? true : false
const isInstanceOfError = (value: unknown) => {
try {
return value instanceof Error
} catch {
return false
}
}
const hasErrorTag = (value: unknown) => {
try {
return ERROR_TAGS.has(Object.prototype.toString.call(value))
} catch {
return false
}
}
const ERROR_TAGS = new Set([
// Cross-realm errors
'[object Error]',
// Browsers
'[object DOMException]',
// Browsers (deprecated)
'[object DOMError]',
// Sentry
'[object Exception]',
])