npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-native-error-handler

v0.1.6

Published

handler react native error

Readme

react-native-error-handler

English | 中文文档

一个用于处理 React Native 错误的库,提供错误边界和全局错误处理功能。

功能特性

  • 🛡️ 错误边界 (ErrorBoundary): 捕获 React 组件树中的 JavaScript 错误
  • 🌐 全局错误处理: 捕获未处理的 JavaScript 错误和 Promise 拒绝
  • 🔧 Promise 修补: 解决 React Native Promise 版本不匹配问题
  • 📱 跨平台支持: 支持 iOS 和 Android 平台
  • 🎨 自定义错误页面: 支持自定义错误回退组件
  • 📊 详细错误信息: 提供错误堆栈、时间戳、平台信息等上下文

项目结构

src/
├── components/
│   └── ErrorBoundary/           # 错误边界组件
│       ├── DefaultFallback/     # 默认错误回退组件
│       │   ├── index.tsx        # 组件实现
│       │   └── styles.ts        # 样式定义
│       └── index.tsx            # 错误边界主组件
├── handlers/                    # 错误处理器
│   ├── setupErrorUtilsGlobalHandler.ts      # 全局错误处理器
│   └── setupUnhandledRejectionsTracking.ts  # 未处理拒绝跟踪
├── types/
│   └── index.ts                 # TypeScript 类型定义
├── utils/                       # 工具函数
│   ├── environment.ts           # 环境检测
│   ├── error.ts                 # 错误处理工具
│   ├── promisePolyfill.ts       # Promise 修补
│   ├── setupReactNativeErrorHandlers.ts  # 主设置函数
│   ├── toolkit.ts               # 通用工具
│   └── worldwide.ts             # 全局工具
├── __tests__/                   # 测试文件
│   └── index.test.tsx
└── index.tsx                    # 主入口文件

Installation

# npm
npm install react-native-error-handler

# yarn
yarn add react-native-error-handler

Usage

基础用法

1. 错误边界 (ErrorBoundary)

错误边界用于捕获 React 组件树中的 JavaScript 错误,防止整个应用崩溃。

import React from 'react';
import { ErrorBoundary } from 'react-native-error-handler';

// 自定义错误回退组件
const CustomFallback = ({ resetError }) => (
  <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
    <Text>出现错误,请重试</Text>
    <Button title="重试" onPress={resetError} />
  </View>
);

function App() {
  return (
    <ErrorBoundary
      FallbackComponent={CustomFallback}
      onError={(errorInfo) => {
        console.log('捕获到错误:', errorInfo);
        // 这里可以上报错误到异常监控服务
        // reportError(errorInfo);
      }}
    >
      <YourAppComponents />
    </ErrorBoundary>
  );
}

2. 全局错误处理

设置全局错误处理器来捕获未处理的 JavaScript 错误和 Promise 拒绝。

import { setupReactNativeErrorHandlers } from 'react-native-error-handler';

// 在应用启动时设置全局错误处理
setupReactNativeErrorHandlers(
  {
    enableGlobalErrorHandler: true,    // 启用全局错误处理
    enableUnhandledRejection: true,   // 启用未处理 Promise 拒绝处理
    patchGlobalPromise: true,         // 修补全局 Promise
    enableInDev: true,                // 在开发模式下启用
  },
  (errorInfo) => {
    console.log('全局错误:', errorInfo);
    // 上报错误到异常监控服务
    // reportError(errorInfo);
  }
);

完整示例

import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import {
  ErrorBoundary,
  setupReactNativeErrorHandlers
} from 'react-native-error-handler';

// 自定义错误回退组件
const CustomErrorFallback = ({ resetError }) => (
  <View style={styles.errorContainer}>
    <Text style={styles.errorTitle}>应用出现错误</Text>
    <Text style={styles.errorMessage}>
      很抱歉,应用遇到了问题。请点击重试按钮重新加载。
    </Text>
    <Button title="重试" onPress={resetError} />
  </View>
);

// 设置全局错误处理
setupReactNativeErrorHandlers(
  {
    enableGlobalErrorHandler: true,
    enableUnhandledRejection: true,
    patchGlobalPromise: true,
    enableInDev: true,
  },
  (errorInfo) => {
    console.error('全局错误捕获:', errorInfo);

    // 错误信息包含以下字段:
    // - error: Error 对象
    // - isFatal: 是否为致命错误
    // - type: 错误类型 ('error' | 'unhandledrejection')
    // - timestamp: 错误发生时间戳
    // - context: 额外的上下文信息(平台、堆栈等)

    // 可以在这里上报错误到异常监控服务
    // reportError(errorInfo);
  }
);

function App() {
  return (
    <ErrorBoundary
      FallbackComponent={CustomErrorFallback}
      onError={(errorInfo) => {
        console.error('组件错误捕获:', errorInfo);
        // 处理组件级别的错误
      }}
    >
      <View style={styles.container}>
        <Text>您的应用内容</Text>
        {/* 您的应用组件 */}
      </View>
    </ErrorBoundary>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  errorTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  errorMessage: {
    fontSize: 14,
    textAlign: 'center',
    marginBottom: 20,
  },
});

配置选项

ErrorHandlerOptions

interface ErrorHandlerOptions {
  /** 是否启用全局错误处理 */
  enableGlobalErrorHandler?: boolean;
  /** 是否启用未处理的 Promise 拒绝处理 */
  enableUnhandledRejection?: boolean;
  /** 是否在开发模式下启用 */
  enableInDev?: boolean;
  /** 是否修补全局 Promise(用于解决 React Native Promise 版本不匹配问题) */
  patchGlobalPromise?: boolean;
}

ErrorInfo

interface ErrorInfo {
  /** 错误对象 */
  error: Error;
  /** 是否为致命错误 */
  isFatal?: boolean;
  /** 错误类型 */
  type: 'error' | 'unhandledrejection';
  /** 错误发生时间戳 */
  timestamp: number;
  /** 额外的上下文信息 */
  context?: Record<string, any>;
}

使用说明

最佳实践

  1. 在应用根组件使用 ErrorBoundary

    // 在 App.js 或 index.js 中
    <ErrorBoundary onError={handleError}>
      <App />
    </ErrorBoundary>
  2. 在应用启动时设置全局错误处理

    // 在 index.js 或 App.js 的顶部
    import { setupReactNativeErrorHandlers } from 'react-native-error-handler';
    
    setupReactNativeErrorHandlers(
      { enableGlobalErrorHandler: true, enableUnhandledRejection: true },
      (errorInfo) => {
        // 上报错误到监控系统
      }
    );
  3. 错误上报集成

    const reportError = (errorInfo) => {
      // 发送到异常监控服务(如 Bugsnag、Firebase Crashlytics 等)
      // 示例:使用 Sentry
      // Firebase.captureException(errorInfo.error, {
      //   extra: {
      //     isFatal: errorInfo.isFatal,
      //     type: errorInfo.type,
      //     timestamp: errorInfo.timestamp,
      //     context: errorInfo.context,
      //   }
      // });
    
      // 示例:上报自定义监控服务
      fetch('/api/errors', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          error: errorInfo.error.message,
          stack: errorInfo.error.stack,
          isFatal: errorInfo.isFatal,
          type: errorInfo.type,
          timestamp: errorInfo.timestamp,
          context: errorInfo.context,
        }),
      });
    };

注意事项

  • 开发环境: 默认情况下,全局错误处理在开发模式下会被禁用,可以通过 enableInDev: true 启用
  • Promise 修补: 如果遇到 Promise 相关的问题,建议启用 patchGlobalPromise: true
  • 错误边界限制: 错误边界只能捕获子组件树中的错误,无法捕获以下错误:
    • 事件处理器中的错误
    • 异步代码中的错误(如 setTimeout、Promise)
    • 服务端渲染期间的错误
    • 错误边界自身的错误

故障排除

常见问题

  1. 错误边界不工作

    • 确保 ErrorBoundary 包装了可能出错的组件
    • 检查是否正确导入了组件
  2. 全局错误处理不生效

    • 确保在应用启动早期调用了 setupReactNativeErrorHandlers
    • 检查配置选项是否正确设置
  3. Promise 相关错误

    • 启用 patchGlobalPromise: true 选项
    • 检查 React Native 版本兼容性

API 参考

ErrorBoundary Props

| 属性 | 类型 | 必需 | 描述 | |------|------|------|------| | onError | (errorInfo: ErrorInfo) => void | 否 | 错误回调函数 | | FallbackComponent | ComponentType<{ resetError: () => void }> | 否 | 自定义错误回退组件 |

setupReactNativeErrorHandlers 参数

| 参数 | 类型 | 默认值 | 描述 | |------|------|--------|------| | options.enableGlobalErrorHandler | boolean | true | 启用全局错误处理 | | options.enableUnhandledRejection | boolean | true | 启用未处理 Promise 拒绝处理 | | options.enableInDev | boolean | true | 在开发模式下启用 | | options.patchGlobalPromise | boolean | true | 修补全局 Promise | | callback | ErrorCallback | - | 错误回调函数 |

Contributing

License

MIT


Made with create-react-native-library

Some code comes from sentry-react-native

Some code comes from es-toolkit