File size: 1,211 Bytes
9e4583c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | /**
* Normalize upstream error bodies to a JSON-safe payload.
* Accepts unknown/object/string inputs and guarantees an { error: { ... } } shape.
*/
export function toJsonErrorPayload(rawError, fallbackMessage = "Upstream provider error") {
const fallback = {
error: {
message: fallbackMessage,
type: "upstream_error",
code: "upstream_error",
},
};
if (rawError && typeof rawError === "object") {
const errorObj = rawError.error;
if (typeof errorObj === "string") {
return {
error: {
message: errorObj,
type: "upstream_error",
code: "upstream_error",
},
};
}
if (errorObj && typeof errorObj === "object") {
return rawError;
}
return { error: rawError };
}
if (typeof rawError === "string") {
const trimmed = rawError.trim();
if (!trimmed) {
return fallback;
}
try {
const parsed = JSON.parse(trimmed);
return toJsonErrorPayload(parsed, fallbackMessage);
} catch {
return {
error: {
message: trimmed,
type: "upstream_error",
code: "upstream_error",
},
};
}
}
return fallback;
}
|