(error: unknown)
| 44 | } |
| 45 | |
| 46 | export function describeError(error: unknown): ErrorDescription { |
| 47 | const stringForm = clip(safeString(error), 400); |
| 48 | |
| 49 | if (!(error instanceof Error) && !(error && typeof error === "object")) { |
| 50 | return { |
| 51 | name: typeof error, |
| 52 | message: "", |
| 53 | stringForm, |
| 54 | brief: stringForm || "<empty>", |
| 55 | }; |
| 56 | } |
| 57 | |
| 58 | const obj = error as Record<string, unknown>; |
| 59 | const nameFromField = readString(obj.name); |
| 60 | const nameFromCtor = error?.constructor?.name; |
| 61 | const name = nameFromField ?? nameFromCtor ?? "Error"; |
| 62 | |
| 63 | const message = readString(obj.message) ?? ""; |
| 64 | const status = readString(obj.status) ?? readString(obj.statusCode); |
| 65 | const code = readString(obj.code); |
| 66 | |
| 67 | let causeName: string | undefined; |
| 68 | const cause = obj.cause; |
| 69 | if (cause && typeof cause === "object") { |
| 70 | const causeRecord = cause as Record<string, unknown>; |
| 71 | causeName = |
| 72 | readString(causeRecord.name) ?? |
| 73 | (cause as { constructor?: { name?: string } }).constructor?.name; |
| 74 | } |
| 75 | |
| 76 | const stack = readString(obj.stack); |
| 77 | const stackHead = stack |
| 78 | ? stack |
| 79 | .split("\n") |
| 80 | .slice(0, 4) |
| 81 | .map((l) => l.trim()) |
| 82 | .filter((l) => l.length > 0) |
| 83 | .join(" | ") |
| 84 | : undefined; |
| 85 | |
| 86 | const briefParts: string[] = []; |
| 87 | if (name) briefParts.push(name); |
| 88 | if (message) briefParts.push(`message="${clip(message, 200)}"`); |
| 89 | if (status) briefParts.push(`status=${status}`); |
| 90 | if (code) briefParts.push(`code=${code}`); |
| 91 | if (causeName) briefParts.push(`cause=${causeName}`); |
| 92 | if (!message && stringForm && stringForm !== name) { |
| 93 | briefParts.push(`str="${clip(stringForm, 200)}"`); |
| 94 | } |
| 95 | const brief = briefParts.join(" ") || stringForm || name; |
| 96 | |
| 97 | return { |
| 98 | name, |
| 99 | message, |
| 100 | ...(status ? { status } : {}), |
| 101 | ...(code ? { code } : {}), |
| 102 | ...(causeName ? { causeName } : {}), |
| 103 | ...(stackHead ? { stackHead } : {}), |
no test coverage detected