add specific message for failure to convert to JSON

This commit is contained in:
buzz-lightsnack-2007 2024-05-25 00:01:58 +08:00
parent a377d28da8
commit eedd53aba4

View file

@ -8,7 +8,7 @@ import logging from "/scripts/logging.js";
export default class net {
/*
Download a file from the network or locally.
@param {string} URL the URL to download
@param {string} TYPE the expected TYPE of file
@param {boolean} VERIFY_ONLY whether to verify the file only, not return its content
@ -17,21 +17,21 @@ export default class net {
*/
static async download(URL, TYPE, VERIFY_ONLY = false, STRICT = false) {
let CONNECT, DATA;
let HEADERS = {};
// If TYPE is used as headers, then the other parts of the header should be taken out for later usage.
let HEADERS = {};
// If TYPE is used as headers, then the other parts of the header should be taken out for later usage.
if (TYPE && (typeof TYPE).includes(`obj`)) {
HEADERS = TYPE;
TYPE = HEADERS[`Content-Type`];
}
try {
// Fetch the file. Add headers when defined.
// Fetch the file. Add headers when defined.
(Object.keys(HEADERS).length) ? CONNECT = await fetch(URL, {method: `POST`, headers: HEADERS}) : CONNECT = await fetch(URL);
if (CONNECT.ok && !VERIFY_ONLY) {
DATA = await CONNECT[(TYPE.toLowerCase().includes('blob')) ? `blob` : `text`]();
if (TYPE
? (TYPE.toLowerCase().includes(`json`) || TYPE.toLowerCase().includes(`dictionary`))
: false) {
@ -40,9 +40,9 @@ export default class net {
} catch(err) {
// When not in JSON, run this.
if (STRICT) {
// Should not allow the data to be returned since it's not correct.
// Should not allow the data to be returned since it's not correct.
DATA = null;
throw new TypeError(texts.localized(`error_msg_notJSON`, false));
throw err;
} else {
logging.warn(texts.localized(`error_msg_notJSON`, false));
}
@ -54,7 +54,7 @@ export default class net {
} catch(err) {
throw err;
}
// Return the filter.
return VERIFY_ONLY ? CONNECT.ok : DATA;
}