js: Factor out getResponseError utility function

This function factors out the logic of extracting an error message from
a `Response` object into a reusable utility function.  This will allow
other pages to use the same logic without duplicating it.
bugfix/ci-buildah
Dustin 2025-03-10 18:22:32 -05:00
parent 20185bdf1f
commit a475f58def
2 changed files with 19 additions and 15 deletions

16
js/ajaxUtil.ts Normal file
View File

@ -0,0 +1,16 @@
export async function getResponseError(r: Response): Promise<string> {
let ct = r.headers.get("Content-Type");
if (ct && ct.indexOf("json") > -1) {
const json = await r.json();
if (json.error) {
return json.error;
}
}
const html = await r.text();
if (html) {
const doc = new DOMParser().parseFromString(html, "text/html");
return doc.documentElement.textContent ?? "";
} else {
return r.statusText;
}
}

View File

@ -12,6 +12,7 @@ import CameraInput from "./camera.ts";
import SlButton from "@shoelace-style/shoelace/dist/components/button/button.js";
import { notify, notifyError } from "./alert";
import { getResponseError } from "./ajaxUtil.js";
const form = document.forms[0];
const cameraInput = form.querySelector("camera-input") as CameraInput;
@ -49,21 +50,8 @@ form.addEventListener("submit", async (evt) => {
notify("Successfully uploaded receipt", undefined, undefined, null);
window.location.href = "/receipts";
} else {
let ct = r.headers.get("Content-Type");
if (ct && ct.indexOf("json") > -1) {
const json = await r.json();
if (json.error) {
notifyError(json.error);
return;
}
}
const html = await r.text();
if (html) {
const doc = new DOMParser().parseFromString(html, "text/html");
notifyError(doc.body.textContent ?? "");
} else {
notifyError(r.statusText);
}
const err = await getResponseError(r);
notifyError(err);
}
});