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