autotel
Version:
Write Once, Observe Anywhere
62 lines (60 loc) • 2.27 kB
JavaScript
import { _ as readProperty, i as asNumber, l as asString, s as asRecord } from "./values-xBtdXtjA.js";
//#region src/parse-error.ts
/** An HTTP-ish status, however the library that threw chose to spell it. */
function toStatus(value) {
const text = asString(value);
return text === void 0 ? asNumber(value) : asNumber(Number(text)) ?? void 0;
}
function pickString(value) {
const text = asString(value);
return text !== void 0 && text.length > 0 ? text : void 0;
}
function pickCode(value) {
return asString(value) ?? asNumber(value);
}
/**
* A plain object of extra fields. Only a plain one: an Error, a Response or a
* class instance carries behaviour, and copying it onto a log line as details
* would serialise something the thrower never meant to publish.
*/
function pickDetails(value) {
const record = asRecord(value);
return record?.constructor === Object ? record : void 0;
}
function parseError(error) {
if (error instanceof Error) {
const structured = error;
return {
message: error.message || "An error occurred",
status: toStatus(structured.status) ?? 500,
why: pickString(structured.why),
fix: pickString(structured.fix),
link: pickString(structured.link),
code: pickCode(structured.code),
details: pickDetails(structured.details),
raw: error
};
}
const err = asRecord(error);
if (err) {
const data = asRecord(err.data);
const payload = asRecord(readProperty(data, "data")) ?? data;
return {
message: pickString(data?.statusText) || pickString(data?.statusMessage) || pickString(data?.message) || pickString(payload?.statusText) || pickString(payload?.statusMessage) || pickString(payload?.message) || pickString(err.message) || "An error occurred",
status: toStatus(payload?.status) || toStatus(payload?.statusCode) || toStatus(err.status) || toStatus(err.statusCode) || 500,
why: pickString(payload?.why) || pickString(err.why),
fix: pickString(payload?.fix) || pickString(err.fix),
link: pickString(payload?.link) || pickString(err.link),
code: pickCode(payload?.code) || pickCode(err.code),
details: pickDetails(payload?.details) || pickDetails(err.details),
raw: error
};
}
return {
message: String(error),
status: 500,
raw: error
};
}
//#endregion
export { parseError };