Errors and Debugging
Trace failures, preserve context, validate assumptions, and debug systematically.
Debugging is the process of narrowing the distance between what the program did and what you expected. Start from evidence, reproduce reliably, and change one assumption at a time.
Throw useful errors
progress.js
function progressPercent(completed, total) {
if (!Number.isFinite(total) || total <= 0) {
throw new TypeError("total must be a positive number");
}
return Math.round((completed / total) * 100);
}
Throw when a function cannot fulfill its contract. Include the invalid concept and expected condition without exposing secrets or private data.
Catch where recovery is possible
settings.js
function readSettings(raw) {
try {
return JSON.parse(raw);
} catch (error) {
console.warn("Settings were invalid; defaults restored", error);
return { theme: "system" };
}
}
Do not catch every error at every level. Catch where you can retry, use a fallback, clean up, or present actionable feedback.
Use the debugger
- Read the first error and its full stack trace.
- Reproduce the smallest failing case.
- Set a breakpoint before the incorrect value appears.
- Inspect scope, call stack, network requests, and DOM state.
- Add a focused test before fixing a regression.
- Verify the fix under the original conditions.
inspection.js
console.table(courses);
console.assert(total >= completed, "Completed lessons exceed total");
Keep this
Define contracts, preserve error context, catch only where recovery exists, and debug from observable evidence.
学习位置已保存在此设备上。