Skip to content
Spotify - 每月低于 10 元

第11章 异常

异常介绍

js
console.log(a); // ReferenceError: a is not defined
let people = undefined;
console.log(people.name);   // TypeError: Cannot read property 'name' of undefined

捕获异常

  • 使用 try...catch 可以捕获异常
js
try {
  var people = undefined;
  console.log(people.name);
} catch (e) {
  console.log('出错了!');
} finally {
  console.log('这里的代码总会执行!');
}

console.log('这行也会执行!');

抛出异常

使用 throw 可以捕获异常

js
function fetchData() {
  console.log('获取数据...');
  throw '404';
}

try {
  fetchData();
} catch (e) {
  if (e === '404') {
    console.error('发生404错误了!');
  }
}

Error 对象

js
class ApiError extends Error {
  constructor(url, ...params) {
    super(...params);
    this.url = url;
    this.name = 'ApiError';
  }
}

function fetchData() {
  console.log('获取数据...');
  throw new ApiError('/post', '404'); // url,message属性
}

try {
  fetchData();
} catch (e) {
  console.error(e); // ApiError: 404
  console.error(e.name); // ApiError
  console.error(e.message); // 404
  console.error(e.url); // /post
}

捕获多个异常

  • 通过 instanceof 可以判断异常的类型
js
class ApiError extends Error {
  constructor(url, ...params) {
    super(...params);
    this.url = url;
    this.name = 'ApiError';
  }
}

function fetchData() {
  console.log('获取数据...');
  console.log(a);
  throw new ApiError('/post', '404');
}

try {
  fetchData();
} catch (e) {
  if (e instanceof ReferenceError) {
    console.log('程序异常');
  } else if (e instanceof ApiError) {
    console.log('API异常');
  }
}
关注微信公众号搬瓦工 - 美国 CN2 优化线路
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0

预览:

评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v3.1.3