| 6 | * filesystem ENOENT) is surfaced rather than silently dropped. |
| 7 | */ |
| 8 | export function getErrorMessage(error: unknown): string { |
| 9 | if (!(error instanceof Error)) { |
| 10 | if (typeof error === "object" && error !== null) { |
| 11 | try { |
| 12 | const errorRecord = error as Record<string, unknown>; |
| 13 | const message = errorRecord.message; |
| 14 | if (typeof message === "string" && message.length > 0) { |
| 15 | return message; |
| 16 | } |
| 17 | |
| 18 | const serializedError = JSON.stringify(error); |
| 19 | if (typeof serializedError === "string") { |
| 20 | return serializedError; |
| 21 | } |
| 22 | // `JSON.stringify` can return undefined (for example when toJSON returns |
| 23 | // undefined), so keep the string-return contract by falling back below. |
| 24 | } catch { |
| 25 | // Accessing properties on arbitrary thrown values (for example Proxies or |
| 26 | // throwing getters) can itself throw. Keep this helper non-throwing and |
| 27 | // fall back to String(error) below. |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | return String(error); |
| 32 | } |
| 33 | |
| 34 | let msg = error.message; |
| 35 | // Guard against cyclic cause chains (e.g. err.cause = err) with a visited set. |
| 36 | const seen = new WeakSet<Error>(); |
| 37 | seen.add(error); |
| 38 | let current: unknown = error.cause; |
| 39 | while (current instanceof Error) { |
| 40 | if (seen.has(current)) break; |
| 41 | seen.add(current); |
| 42 | const causeMessage = current.message; |
| 43 | // Some wrapped SDK errors stringify a plain object to "[object Object]", |
| 44 | // which adds noise without surfacing any actionable context. |
| 45 | if (causeMessage && causeMessage !== "[object Object]" && !msg.includes(causeMessage)) { |
| 46 | msg += ` [cause: ${causeMessage}]`; |
| 47 | } |
| 48 | current = current.cause; |
| 49 | } |
| 50 | return msg; |
| 51 | } |