CodeRoadMap
首页路线题库资源库文章社区
CodeRoadMap

程序员的学习成长路线图。内容免费开放,登录后可同步路线图与课时进度。

由 程序员柏风 独立维护 · 关于作者

学习

  • 路线图
  • 课程
  • 面试题
  • 文章
  • 我

更多

  • 资源
  • 社区
  • 关于作者
  • 内容说明

© 2026 CodeRoadMap

津ICP备2026012044号-1·津公网安备12011002026155号·coderoadmap@126.com
JavaScript 进阶/课时/调试与异常
RawBlame
课时目录12 节

JavaScript 进阶

  1. 01JS 进阶地图
  2. 02变量与提升
  3. 03运算符与相等
  4. 04控制流深入
  5. 05函数与 this
  6. 06异步深入
  7. 07对象与原型
  8. 08集合与 JSON
  9. 09模块系统
  10. 10内存与 GC
  11. 11调试与异常
  12. 12综合练习

调试与异常

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 调试

  1. Performance → Record → 复现卡顿 → Stop
  2. 查看 Long Task(>50ms)、Layout Shift
  3. Main 线程火焰图找耗时函数

React DevTools Profiler 可定位重渲染;本课侧重原生 Performance。

Node 调试

node --inspect-brk app.js
# Chrome 打开 chrome://inspect 附加调试器

与浏览器断点体验一致,适合 nodejs-essentials 脚本。

错误边界思想

// 浏览器:window.onerror / unhandledrejection
window.addEventListener('unhandledrejection', (e) => {
  console.error('未处理的 Promise 拒绝', e.reason);
});

// React Error Boundary 在 react-essentials 展开

全局 handler 用于上报 Sentry 等,不替代局部 try/catch。

练习

  • 对含 bug 的 flatMap 设条件断点,修掉 undefined.lessons
  • 写自定义 ValidationError,在 catch 里按类型分支处理
  • 录一段 Performance,找出一次 click 后的 long task

小结

断点 + Network 查异步;try/catch 结构化错误;Performance 查卡顿。 下一课综合练习。

加载本节练习…
← 上一课内存与 GC下一课 →综合练习