HLJ 发布于
2025-06-11 10:57:08
0阅读

JavaScript Promise 错误处理方法

JavaScript 使用 Promise 进行错误处理

Promise 是 JavaScript 中处理异步操作的重要机制,良好的错误处理是 Promise 使用的关键部分。以下是 Promise 错误处理的几种主要方式:

1. 使用 .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);
  });

2. 在 .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);
  });

3. 使用 try/catchasync/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();

4. Promise 链中的错误传播

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));

5. 全局未捕获的 Promise 错误

可以使用 unhandledrejection 事件捕获未被处理的 Promise 拒绝:

window.addEventListener('unhandledrejection', event => {
  console.warn('Unhandled promise rejection:', event.reason);
  // 可以在这里进行错误上报等操作
  event.preventDefault(); // 阻止默认行为(如控制台报错)
});

6. Promise 错误处理最佳实践

  1. 总是返回 Promise 链:确保每个 .then() 返回一个值或 Promise
  2. 不要忽略错误:即使只是记录日志,也要处理错误
  3. 区分操作错误和编程错误:操作错误是可预期的(如网络问题),编程错误是 bug
  4. 提供有意义的错误信息:错误对象应包含足够信息用于调试
  5. 考虑错误恢复:某些错误可能可以恢复或重试

7. 示例:综合错误处理

function 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 应用程序。

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2025-06-11/831.html
最后生成于 2025-06-13 20:53:43
此内容有帮助 ?
0