chrisblakley / Nebula

Nebula is a WordPress theme framework that focuses on enhancing development. The core features of Nebula make it a powerful tool for designing, developing, and analyzing WordPress websites consistently, yet its deliberately uncomplicated code syntax also serves as a learning resource for programmers themselves.
https://nebula.gearside.com
GNU General Public License v3.0
144 stars 36 forks source link

Consider an error method on the Nebula Fetch JS functionality #2297

Closed chrisblakley closed 2 months ago

chrisblakley commented 2 months ago

Consider adding a .error() method that can be attached to the nebula.fetch() function just like a native JS fetch.

Probably something like this, but untested:

nebula.fetch = async function(url = false, headers = {}, type = 'json') {
    if (!url) {
        nebula.help('nebula.fetch() requires a URL to retrieve.', '/functions/fetch/');
        return false;
    }

    if (typeof headers !== 'object') { // If the type is passed as the second parameter
        type = headers;
        headers = {};
    }

    const fetchLabel = nebula.sanitize(url);
    window.performance.mark('(Nebula) Fetch Start ' + fetchLabel);

    // Creating a new promise to handle fetch
    let fetchPromise = new Promise(async (resolve, reject) => {
        try {
            let response = await fetch(url, headers);

            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.statusText);
            }

            let data;
            if (type === 'json') {
                data = await response.json();
            } else {
                data = await response.text();
            }

            window.performance.mark('(Nebula) Fetch End ' + fetchLabel);
            window.performance.measure('(Nebula) Fetch ' + url, '(Nebula) Fetch Start ' + fetchLabel, '(Nebula) Fetch End ' + fetchLabel);

            resolve(data);
        } catch (error) {
            reject(error);
        }
    });

    // Adding an .error method to handle errors
    fetchPromise.error = function(message, callback) {
        return fetchPromise.catch((err) => {
            console.error(message, err);
            if (typeof callback === 'function') {
                callback(err);
            }
        });
    };

    return fetchPromise;
};