error handling with exceptions
by lovinglobo
JavaScript
function isNumber(str) {
return (parseInt(str) + "") === str;
}
function isNorwegianPostalCode(str) {
return isNumber(str) && str.length === 4;
}
function sendPackage(firstName, surName, postalCode, itemNr) {
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) {
return errors;
}
checkInStock(itemNr);
// do some work
console.log("Sending package...");
}
function sendBill(firstName, accountNr) {
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...");
}
try {
sendPackage("Jalando", "St. James", "1162", "20");
sendBill("Jalando", "123457890");
console.log("Hooray, we've sent the package");
} catch(errors) {
console.log(`Woooppzz something went wrong`, errors);
}