about summary refs log blame commit diff stats
path: root/js/catchError.js
blob: 0f833aef85f66d806988262ad7a7b50fa03ec186 (plain) (tree)




















































                                                                  
// handle errors in async functions without using try/catch
function catchError(promise) {
    return promise
      .then(data => [undefined, data])
      .catch(error => [error]);
}











// Examples

function examplePromise(success) {
    return new Promise((resolve, reject) => {
        if (success) {
            resolve("Data loaded successfully!");
        } else {
            reject("Failed to load data.");
        }
    });
}
  
async function runExample() {
    const [error, data] = await catchError(examplePromise(true));

    if (error) {
        console.error("Error:", error);
    } else {
        console.log("Success:", data);
    }
}

runExample();

async function runExample2() {
    const [error, data] = await catchError(examplePromise(false));

    if (error) {
        console.error("Error:", error);
    } else {
        console.log("Success:", data);
    }
}

runExample2();