js错误类型分类
- Error
- EvalError
- InternalError
- RangeError
- ReferenceError
- SyntaxError
- TypeError
- URIError
日常开发常用的错误对象
new Error();
new TypeError();
- 错误对象的基本有以下属性,在错误被抛出,可以在日志中看到;
-
- message 错误信息
- name 错误类型
- stack 错误堆栈
错误对象被Throw才会出现异常
如何优雅捕获异常错误
同步情况下
- try catch 优雅处理
function toUppercase(string) {
if(typeof string !== "string") {
throw TypeError('ssss')
}
return string.toUppercase()
}
try {
toUppercase(1)
} catch(error) {
console.error(error)
}
异步情况下
因为js是单进程的,异步情况下,try catch是同步写法,不能捕获错误;
- 回调地狱
function AsyncTask() {
asyncFuncA(function(err, resultA){
if(err) return cb(err);
asyncFuncB(function(err, resultB){
if(err) return cb(err);
asyncFuncC(function(err, resultC){
if(err) return cb(err);
// And so it goes....
});
});
});
}
- promise
function asyncTask(cb) {
asyncFuncA.then(AsyncFuncB)
.then(AsyncFuncC)
.then(AsyncFuncD)
.then(data => cb(null, data)
.catch(err => cb(err));
}
- await + try catch
async function getUser() {
try {
return await getUser();
} catch(e) {
console.log(e)
}
}
- 如果不想用await + try catch; 可以封装一个处理错误函数包裹
function to(promise) {
return promise.then(data => {
return [null, data];
})
.catch(err => [err]);
}
function getUser() {
const [err, user] = await to(getUser());
if(err) throw new CustomerError('No user found');
}
for | forEach中如何中断循环
for
- continue break return;
// break 跳出整个循环
const a = [1,2,3,4];
for(let i= 0;i<a.length;i++) {
if(i === 2) break;
console.log(i)
}
// 0 1
// continue 跳出当次循环
const a = [1,2,3,4];
for(let i= 0;i < a.length;i++) {
if(i === 2) continue;
console.log(i)
}
// 0 1 3
// return 函数直接return;跳出整个循环
function test() {
const a = [1,2,3,4];
for(let i= 0;i < a.length;i++) {
if(i === 2) return;
console.log(i)
}
}
test()
forEach
- 在forEach中使用关键字continue break会报语法错误;
- return 可以跳出当前循环;因为forEach是ES6提供的对array处理的function操作;每次迭代都执行该函数,所以return,只是跳出当前循环
array.forEach(callback(item, index,array));
- throw Error可以跳出整个循环
const a = [1,2,3,4];
try {
a.forEach(i => {
if(i === 2) throw new Error('demo');
console.log(i)
})
} catch(e) {
console.log(e)
}