JS错误处理
一、错误传递
要进行错误处理先要了解错误的传播机制以及错误类型
当一个函数发生错误时,但是外层却没有使用try..catch捕获,那么错误就会被抛向外层调用的函数,若一直没有被捕获则该错误就会沿着调用链向上抛出,直到被js引擎捕获。
try-catch-finally
try{
// 尝试执行的代码
if(条件){
throw new Error('自定义错误')
}
}catch(e){
// 出错时执行
console.error('An error occurred:', error.message);
}finally {
// 不论是否出错都会执行
}
二、异步错误处理
在 JavaScript 中,异步函数外部的 try...catch 无法捕获异步操作中的错误
function print(){
consloe.log('a')
}
try{
setTimeout(print,1000)
console.log('b')
}catch (e){
console.log('c')
}
console.log('d')
上述代码的执行结果是先b后a,若在print中发生了错误,由于setTimeout是异步的,所以使用通过Try...catch是无效的。这是应为调用setTimeout函数后,print函数不会立即执行,而是要1秒后才会执行。此时代码会继续向下执行console.log('b'),一秒后print发生错误,但此时try...catch已经执行完,此时除了在printTime函数内部捕获错误外,外层代码并无法捕获。
所以,涉及到异步代码,无法在调用时捕获,原因就是在捕获的当时,回调函数并未执行。
正确捕获异步错误
这时我们可以使用Promise,或者async/await来处理,本质上是让异步变成类似同步的行为。或者直接在异步函数内部使用try...catch
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchData();