Intermediate · 12 min
Validate input and handle errors
Reject invalid input deliberately and recover at an appropriate boundary.
Signal a problem
throw stops the current path and sends an error to the nearest matching catch. Validate values before calculating with them.
function quantity(value) {
if (!Number.isInteger(value) || value < 0) throw new Error("Invalid quantity");
return value;
}
try { console.log(quantity(-1)); } catch (error) { console.log(error.message); }Output
Invalid quantity
Handle expected failures
Catch a failure where you can respond usefully. Avoid silently replacing every failure with a success value. finally runs when leaving the try/catch, including after an error.
try {
JSON.parse("invalid");
} catch {
console.log("Invalid JSON");
} finally {
console.log("Finished");
}Output
Invalid JSON Finished
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Reject a negative quantity
Make validate throw an Error with the message "Invalid quantity" when value is negative.
Reject every value below 0.