Promise 是 JavaScript 中处理异步操作的重要机制,良好的错误处理是 Promise 使用的关键部分。以下是 Promise 错误处理的几种主要方式:
.catch()
方法.catch()
是专门用于处理 Promise 链中错误的方法:
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('There was a problem with the fetch operation:', error);
});
.then()
中使用第二个参数.then()
方法接受两个参数,第二个参数是错误处理函数:
fetch('https://api.example.com/data')
.then(
response => {
// 成功处理
return response.json();
},
error => {
// 只处理这个 then 之前的错误
console.error('Fetch failed:', error);
}
)
.then(data => {
console.log(data);
});
try/catch
与 async/await
在 async 函数中,可以使用传统的 try/catch 语法:
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('Error fetching data:', error);
}
}
fetchData();
Promise 链中的错误会一直向下传递,直到遇到 .catch()
处理:
doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => console.log(`Got the final result: ${finalResult}`))
.catch(error => console.error('Something failed along the way:', error));
可以使用 unhandledrejection
事件捕获未被处理的 Promise 拒绝:
window.addEventListener('unhandledrejection', event => {
console.warn('Unhandled promise rejection:', event.reason);
// 可以在这里进行错误上报等操作
event.preventDefault(); // 阻止默认行为(如控制台报错)
});
.then()
返回一个值或 Promisefunction fetchUserData(userId) {
return fetch(`https://api.example.com/users/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(user => {
if (!user.active) {
throw new Error('User is inactive');
}
return user;
});
}
async function displayUser(userId) {
try {
const user = await fetchUserData(userId);
console.log('User data:', user);
} catch (error) {
if (error.message.includes('HTTP error')) {
console.error('Network problem:', error);
} else if (error.message.includes('inactive')) {
console.warn('User is inactive');
} else {
console.error('Unknown error:', error);
}
}
}
displayUser(123);
通过合理使用这些错误处理技术,可以构建健壮的异步 JavaScript 应用程序。