Module 3: Conditions and Loops
Reading and Handling Errors
Recognize syntax, reference, type, and application errors and respond clearly.
Errors are useful feedback. A syntax error means the source cannot be parsed; a ReferenceError often means a name is unavailable; a TypeError often means an operation is invalid for a value. Application errors can also represent validation failures, missing records, or failed network requests.
try {
const value = JSON.parse('{"active": true}');
console.log(value.active);
} catch (error) {
console.error("The supplied JSON is invalid.", error);
}
Use try...catch around operations that may throw and where your code can take a useful action, such as displaying a clear message or logging diagnostic details. Do not hide errors with an empty catch block.
Throw meaningful errors#
function divide(a, b) {
if (b === 0) {
throw new Error("The divisor must not be zero.");
}
return a / b;
}
Use the built-in Error type for ordinary errors. Custom error classes can be useful when callers need to distinguish between error categories.
Validate at boundaries#
Check external input before using it. Data from forms, URLs, storage, and HTTP APIs should be treated as untrusted or potentially malformed. A valid JSON document can still have the wrong shape or values for your application.
Practice#
Wrap JSON.parse in error handling and show a user-friendly message when the input is invalid. Keep technical details available for debugging without exposing secrets.