31 lines · 1.3 KBRaw
| 1 | /** |
| 2 | * Failures a caller cannot fix by changing its input. Handles throw these; anything a |
| 3 | * caller can fix and retry is returned as an `Outcome` instead. |
| 4 | * |
| 5 | * Workers RPC keeps only an error's `name` and `message`, so the code travels in the |
| 6 | * message as `refs:<code> <description>`. Callers read it with `refsErrorCode`, never |
| 7 | * with `instanceof`. |
| 8 | */ |
| 9 | export type RefsErrorCode = |
| 10 | /** The resource does not exist, or the actor is not allowed to know that it exists. */ |
| 11 | | "not_found" |
| 12 | /** The operation needs a signed-in human or agent, and the actor is anonymous. */ |
| 13 | | "sign_in_required"; |
| 14 | |
| 15 | const CODES: readonly RefsErrorCode[] = ["not_found", "sign_in_required"]; |
| 16 | |
| 17 | export function refsErrorCode(error: unknown): RefsErrorCode | null { |
| 18 | const message = error instanceof Error ? error.message : typeof error === "string" ? error : ""; |
| 19 | const code = /^refs:([a-z_]+)\b/.exec(message)?.[1]; |
| 20 | return CODES.find((candidate) => candidate === code) ?? null; |
| 21 | } |
| 22 | |
| 23 | /** The human-readable part of a refs error, without its code. */ |
| 24 | export function refsErrorDescription(error: unknown): string { |
| 25 | const message = error instanceof Error ? error.message : String(error); |
| 26 | return message.replace(/^refs:[a-z_]+\s*/, ""); |
| 27 | } |
| 28 | |
| 29 | export function refsErrorMessage(code: RefsErrorCode, description: string): string { |
| 30 | return `refs:${code} ${description}`; |
| 31 | } |