| 4 | * Normalize various error types into a consistent format |
| 5 | */ |
| 6 | export function normalizeError(error: unknown): NormalizedError { |
| 7 | if (error instanceof Error) { |
| 8 | const code = (error as NodeJS.ErrnoException).code |
| 9 | return { |
| 10 | name: error.name, |
| 11 | message: error.message, |
| 12 | ...(error.stack !== undefined ? { stack: error.stack } : {}), |
| 13 | ...(code !== undefined ? { code } : {}), |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | if (typeof error === 'string') { |
| 18 | return { |
| 19 | name: 'Error', |
| 20 | message: error, |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | if (typeof error === 'object' && error !== null) { |
| 25 | const errObj = error as Record<string, unknown> |
| 26 | return { |
| 27 | name: String(errObj.name || 'Error'), |
| 28 | message: String(errObj.message || 'Unknown error'), |
| 29 | ...(errObj['stack'] ? { stack: String(errObj['stack']) } : {}), |
| 30 | ...(errObj['code'] ? { code: String(errObj['code']) } : {}), |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | return { |
| 35 | name: 'UnknownError', |
| 36 | message: String(error), |
| 37 | } |
| 38 | } |