调试与异常
DevTools、try/catch、performance debugging。
30 分钟
调试与异常
javascript-core 用过 console.log;本课系统使用 Chrome DevTools、try/catch/finally 与 Performance 面板。无论浏览器还是 nodejs-essentials,调试技能与 react-essentials 组件排查互通。
学习目标
- 熟练使用断点、条件断点与 watch 表达式
- 结构化错误处理与自定义 Error
- 用 Performance 面板定位长任务与布局抖动
DevTools 断点
function loadLessons(tracks) {
debugger; // 显式断点(生产应移除)
return tracks.flatMap((t) => t.lessons);
}
Sources 面板:
- 行断点:点击行号
- 条件断点:右键 → Add conditional breakpoint(如
slug === 'jsa-async') - Logpoint:不暂停,只打印表达式
Network 面板配合异步:查看 fetch 时序、状态码、响应体。
try / catch / finally
async function fetchLesson(slug) {
try {
const res = await fetch(`/api/tracks/js/lessons/${slug}`);
if (!res.ok) {
throw new HttpError(res.status, await res.text());
}
return await res.json();
} catch (err) {
if (err instanceof HttpError) {
console.error('API 错误', err.status, err.body);
} else if (err.name === 'AbortError') {
console.warn('请求已取消');
} else {
console.error('未知错误', err);
}
throw err; // 或返回 fallback
} finally {
hideSpinner();
}
}
class HttpError extends Error {
constructor(status, body) {
super(`HTTP ${status}`);
this.name = 'HttpError';
this.status = status;
this.body = body;
}
}
finally 无论成败都执行,适合清理 UI 状态。
console 进阶
console.table([{ slug: 'jsa-intro', order: 1 }]);
console.time('fetch');
await fetch('/api/tracks');
console.timeEnd('fetch');
console.group('lesson');
console.log('step 1');
console.groupEnd();
生产环境避免留 debugger 与敏感信息 log。
Performance 调试
- Performance → Record → 复现卡顿 → Stop
- 查看 Long Task(>50ms)、Layout Shift
- Main 线程火焰图找耗时函数
React DevTools Profiler 可定位重渲染;本课侧重原生 Performance。