error handling with promises

by lovinglobo

JavaScript

function isNumber(str) {
	return (parseInt(str) + "") === str;
}

function isNorwegianPostalCode(str) {
	return isNumber(str) && str.length === 4;
}

function checkInStock(itemNr) {
	const isInStock = parseInt(itemNr) > 100;
	if (!isInStock) {
  	throw {
    	errorType: "notInStock",
	    message: `Item with itemNr ${itemNr} is not in stock!`
    };
  }
}


function sendPackage(firstName, surName, postalCode, itemNr) {
	return new Promise((resolve, reject) => {
    let errors = [];
    if (firstName.length === 0) {
      errors.push({
        errorType: "firstNameNotValid",
        message: `The given firstName is empty`
      });
    }

    if (surName.length < 1) {
      errors.push({
        errorType: "surNameNotValid",
        message: `The given surName is empty`
      });
    }

    if (!isNorwegianPostalCode(postalCode)) {
      errors.push({
        errorType: "postalCodeNotValid",
        message: `The postal code '${postalCode}' is not valid in Norway.`
      });
    }

    if (errors.length > 0) {
      throw errors;
    }


    checkInStock(itemNr);

    // do some work
    console.log("Sending package...");
    resolve(true);
  });
}

function sendBill(firstName, accountNr) {
	return new Promise((resolve, reject) => {
    let errors = [];
    if (firstName.length === 0) {
      errors.push({
        errorType: "firstNameNotValid",
        message: `The given firstName is empty`
      });
    }

    if (!isNumber(accountNr) || accountNr.length !== 10) {
      errors.push({
        errorType: "accountNrNotValid",
        message: `The given account number is not a ten digit number`
      });
    }

    if (errors.length > 0) {
      throw errors;
    }

    // do some work
    console.log("Sending bill...");
   	resolve(true);
  });
}

sendPackage("Jalando", "St. James", "1162", "20").then(result =>{
	return sendBill("Jalando", "123457890");	
}).then(result => {
	console.log("Hooray, we've sent the package");
}).catch(error => {
	console.log("Got...