Line data Source code
1 : /**
2 : * Narrow an unknown caught value to an Error.
3 : *
4 : * Replaces unsafe `value as Error` assertions. When `value` is not already
5 : * an Error instance, wraps it in a new Error whose message is the stringified
6 : * input so downstream consumers (loggers, Sentry, toasts) always receive a
7 : * usable Error object instead of `undefined.message`.
8 : */
9 109 : export function toError(value: unknown): Error {
10 109 : if (value instanceof Error) return value
11 1 : if (typeof value === 'string') return new Error(value)
12 0 : if (value === undefined) return new Error('undefined')
13 0 : try {
14 0 : const serialised = JSON.stringify(value)
15 0 : return new Error(serialised)
16 : } catch {
17 0 : return new Error(String(value))
18 : }
19 : }
20 :
21 : /**
22 : * Extract a message from an unknown caught value without asserting its type.
23 : * Returns `undefined` when the value carries no usable message.
24 : */
25 4 : export function getErrorMessage(value: unknown): string | undefined {
26 4 : if (value instanceof Error) return value.message
27 0 : if (typeof value === 'string') return value
28 4 : if (
29 : typeof value === 'object' &&
30 : value !== null &&
31 : 'message' in value &&
32 : typeof value.message === 'string'
33 : ) {
34 0 : return value.message
35 : }
36 : return undefined
37 : }
|