You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Expo时网络不佳触发expo-Notification错误,try/catch无效求解决方案

解决Expo Notifications弱网下无法捕获的网络错误

问题背景

弱网环境下,expo-notifications更新设备推送令牌到服务器时会抛出以下未被常规try/catch捕获的错误:

[expo-notifications] error thrown while updating the device push token with the server TypeError: Network request failed

核心原因

该错误由expo-notifications模块后台自动同步令牌的异步任务抛出,不在业务代码的try/catch覆盖范围内,因此常规捕获方式无效。

解决方案

方案1:手动控制令牌同步流程

禁用模块的自动同步逻辑,将令牌获取、同步操作纳入自己的代码流程,从而用try/catch捕获错误:

import * as Notifications from 'expo-notifications';

// 初始化通知处理规则
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

// 禁用自动令牌同步
await Notifications.setAutoRegistrationAsync(false);

// 手动获取并同步令牌
async function syncPushToken() {
  try {
    // 请求通知权限
    const { status } = await Notifications.requestPermissionsAsync();
    if (status !== 'granted') {
      console.log('通知权限未授予');
      return;
    }

    // 获取Expo推送令牌
    const token = await Notifications.getExpoPushTokenAsync({
      projectId: '你的Expo项目ID', // 替换为实际项目ID
    });

    // 同步令牌到你的业务服务器(可选)
    // await fetch('你的服务器同步接口', {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify({ pushToken: token.data }),
    // });

    console.log('令牌同步成功');
  } catch (error) {
    // 捕获网络错误,执行降级逻辑
    console.log('令牌同步失败:', error);
    // 可选:添加重试机制
    setTimeout(syncPushToken, 5000); // 5秒后重试
  }
}

// App启动时执行同步
syncPushToken();

方案2:全局捕获未处理错误

通过React Native的全局错误处理器捕获模块后台抛出的错误:

import { ErrorUtils } from 'react-native';

// 保存默认全局错误处理器
const originalErrorHandler = ErrorUtils.getGlobalHandler();

// 设置自定义全局错误处理
ErrorUtils.setGlobalHandler((error, isFatal) => {
  // 匹配expo-notifications的弱网错误
  if (error.message.includes('[expo-notifications] error thrown while updating the device push token') && error.message.includes('Network request failed')) {
    console.log('捕获到弱网下的推送令牌同步错误:', error);
    // 阻止错误触发崩溃或默认报错逻辑
    return;
  }
  // 其他错误交给默认处理器处理
  originalErrorHandler(error, isFatal);
});

内容的提问来源于stack exchange,提问作者Maged Maher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:32:56