Skip to content

Instantly share code, notes, and snippets.

@geekykant
Last active October 4, 2020 16:06
Show Gist options
  • Save geekykant/a1bb2121eba424144f4cc19921886bd7 to your computer and use it in GitHub Desktop.
Save geekykant/a1bb2121eba424144f4cc19921886bd7 to your computer and use it in GitHub Desktop.
JavaScript πŸ’« - QUICK Codes!

Exception Handling

function makePizza(toppings = []) {
  return new Promise((resolve, reject) => {
    if (toppings.includes("apple")) {
      reject("Sorry apple not available 🍎");
    }

    ms = 1500 + 500 * toppings.length;
    setTimeout(() => {
      resolve(`Your Pizza is ready with toppings πŸ• ${toppings.join(" ")}`);
    }, ms);
  });
}

Method 1 - Then & Catch

makePizza(["cashew", "apple"])
  .then((pizza) => {
    console.log(pizza);
  })
  .catch((error) => {
    console.log("Error occurred");
    console.log(error);
  });

Method 2 - Try & Catch

async function makePizza1() {
  try {
    const pizza = await makePizza(["cashew", "ham", "cheese"]);
    console.log(pizza);
  } catch (error) {
    console.log(error);
  }
}

Method 3 - Handle using handleError function

function handleError(error) {
  console.log("Error occured.");
  console.log(error);
}

async function makePizza1() {
  const pizza = await makePizza(["cashew", "ham", "cheese"]);
  console.log(pizza);
}

async function makePizza2() {
  const pizza = await makePizza(["apple"]);
  console.log(pizza);
}

makePizza1().catch(handleError);
makePizza2().catch(handleError);

Method 4 - MakeSafe fn()

function handleMyError(error) {
  console.log("Error occured.");
  console.log(error);
}

function makeSafe(fn, errorHandler) {
  return function () {
    fn().catch(errorHandler);
  };
}

async function makePizza1() {
  const pizza = await makePizza(["cashew", "ham", "cheese"]);
  console.log(pizza);
}

const makeDinner = makeSafe(makePizza1, handleMyError);
makeDinner();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment