• try catch在实际开发中的5大应用场景总结
  • 发布于 1周前
  • 41 热度
    0 评论
前言
昨天一位群友在面试的时候被问到了这么一个问题:多个请求同时发起时,如何保证失败或者成功都返回,我第一啥时间就想到了 Promise.allSettled 来实现
// 模拟多个异步操作:获取用户基本信息、订单记录、消息通知
const fetchUserInfo = () =>
  fetch('/api/user').then(res => res.json());

const fetchOrders = () =>
  fetch('/api/orders').then(res => {
    if (!res.ok) thrownewError('订单获取失败')
    return res.json()
  });

const fetchNotifications = () =>
newPromise((_, reject) =>
    setTimeout(() => reject(newError('请求超时')), 3000)
  );
// 堆代码 duidaima.com
// 使用 Promise.allSettled 并行执行
Promise.allSettled([
  fetchUserInfo(),
  fetchOrders(),
  fetchNotifications()
])
.then(results => {
const [userResult, ordersResult, notifyResult] = results;

// 处理用户信息
if (userResult.status === 'fulfilled') {
    console.log('用户数据:', userResult.value);
    renderUserProfile(userResult.value);
  } else {
    console.error('用户信息失败:', userResult.reason);
    showPlaceholder('#user-section');
  }

// 处理订单数据
if (ordersResult.status === 'fulfilled') {
    console.log('订单数据:', ordersResult.value);
    renderOrderList(ordersResult.value);
  } else {
    console.error('订单获取失败:', ordersResult.reason);
    showErrorToast('订单加载异常');
  }

// 处理通知数据
if (notifyResult.status === 'fulfilled') {
    console.log('通知数据:', notifyResult.value);
    updateNotificationBadge(notifyResult.value);
  } else {
    console.warn('通知获取失败:', notifyResult.reason);
    disableNotificationBell();
  }
});

/* 输出示例:
用户数据: {id: 1, name: "张三"}
订单数据: [ {...}, {...} ]
通知获取失败: Error: 请求超时
*/
但是他说了:面试官说除了 Promise.allSettled 实现,还有什么其他办法吗? 于是我又想到了使用 try catch + Promise.all:
// 模拟多个异步操作:获取用户基本信息、订单记录、消息通知
const fetchUserInfo = async () => {
    try {
        const res = await fetch('/api/user')
        return res.json()
    } catch {
        returnnull
    }
}

const fetchOrders = async () => {
    try {
        const res = await fetch('/api/orders')
        if (!res.ok) thrownewError('订单获取失败')
        return res.json()
    } catch {
        returnnull
    }
}

const fetchNotifications = async () => {
    try {
        awaitnewPromise((_, reject) =>
            setTimeout(() => reject(newError('请求超时')), 3000)
        )
    } catch {
        returnnull
    }
}

// 使用 Promise.all
Promise.all([
    fetchUserInfo(),
    fetchOrders(),
    fetchNotifications()
]).then(res => {
    console.log(res)
    // [
    //     {id: 1, name: "张三"},
    //     [ {...}, {...} ],
    //     null
    // ]
})
接着这位群友问我能不能出一篇 try catch 在实际开发中的使用场景,我想想其实可以讲讲

try catch 场景
1、异步请求的优雅处理
典型场景: 处理 AJAX/Fetch 请求时网络错误、接口异常
async function fetchUserData() {
try {
    const response = await fetch('/api/user');
    if (!response.ok) thrownewError('HTTP Error');
    const data = await response.json();
    // 正常处理逻辑
  } catch (error) {
    console.error('请求失败:', error);
    showToast('数据加载失败,请检查网络');
    // 降级处理:显示缓存数据/缺省页面
  }
}
2、JSON 解析的安全防护
常见问题: JSON.parse() 遇到非法格式时导致整个应用崩溃
function safeParse(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (e) {
    console.warn('JSON 解析失败,返回默认值');
    return {}; // 或执行其他恢复逻辑
  }
}
// 使用案例
const userPrefs = safeParse(localStorage.getItem('preferences'));
3、第三方库的错误隔离
痛点场景: 不确定稳定性的插件/工具库可能抛出意外错误
function safePluginInit() {
  try {
    ThirdPartyPlugin.init({
      // 复杂配置项
    });
  } catch (e) {
    captureErrorToSentry(e); // 上报错误
    loadFallbackPlugin(); // 降级方案
  }
}
4、表单验证的灵活应用
function validateForm(formData) {
try {
    if (!formData.email.includes('@')) {
      thrownew ValidationError('邮箱格式错误');
    }
    if (formData.password.length < 8) {
      thrownew ValidationError('密码至少8位');
    }
  } catch (e) {
    if (e instanceof ValidationError) {
      highlightErrorField(e.message);
      returnfalse;
    }
    // 其他未知错误继续抛出
    throw e;
  }
}
5、浏览器特性检测的优雅降级
兼容性处理: 替代传统的特性检测写法
function checkWebGLSupport() {
try {
    const canvas = document.createElement('canvas');
    return !!window.WebGLRenderingContext && 
      (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
  } catch (e) {
    returnfalse;
  }
}

if (!checkWebGLSupport()) {
  showCompatibilityWarning();
  load2DFallback();
}


用户评论