Reject invalid data by throwing an error.

Throwing Validation Errors

throw_validation.js
const count = 3;
let status = "";

function requirePositive(value) {
  if (value <= 0) {
    throw new Error("count must be positive");
  }
  return value;
}

try {
  const accepted = requirePositive(count);
  status = "accepted:" + accepted;
} catch (error) {
  status = "rejected";
}

console.log("count=" + count);
console.log("status=" + status);
throw-validation `throw` stops the current path and sends control to the nearest matching `catch`. Validation code often throws when an input is not acceptable.