react-native-comprehensive-error-handler
v1.0.0
Published
Comprehensive error handling for React Native - catches render, sync, and async errors with multi-engine support (Hermes, JSC, Web)
Maintainers
Readme
react-native-comprehensive-error-handler
Comprehensive error handling for React Native - catches render, sync, and async errors with multi-engine support
A robust, production-ready error handling solution that catches all error types in React Native apps:
- ✅ Render errors via Error Boundaries
- ✅ Synchronous errors via Global Error Handler
- ✅ Asynchronous errors via Promise Rejection Tracker
- ✅ Multi-engine support (Hermes, JavaScriptCore, Web)
- ✅ Zero dependencies (React Native peer dependency only)
- ✅ TypeScript support with full type definitions
- ✅ Expo compatible - works out of the box
📦 Installation
Using npm:
npm install react-native-comprehensive-error-handler react-native-safe-area-contextUsing Expo:
npx expo install react-native-comprehensive-error-handler react-native-safe-area-context💡 Note: With npm 7+, peer dependencies install automatically. The above command will install both packages in one go.
🚀 Quick Start
Wrap your app with GlobalErrorBoundary:
import { GlobalErrorBoundary } from 'react-native-comprehensive-error-handler';
function App() {
return (
<GlobalErrorBoundary
onError={(error, errorType, errorInfo) => {
console.log('Error caught:', error);
// Optional: Send to your error reporting service
}}
>
<YourApp />
</GlobalErrorBoundary>
);
}That's it! 🎉 All errors are now caught and handled gracefully.
📖 API Reference
<GlobalErrorBoundary>
The main component that wraps your app and handles all errors.
Props
| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| children | ReactNode | ✅ | - | Your app content |
| config | GlobalErrorBoundaryConfig | ❌ | See below | Error handling configuration |
| onError | (error, errorType, errorInfo) => void | ❌ | - | Callback when error is caught |
| fallbackComponent | ComponentType<FallbackComponentProps> | ❌ | DefaultFallback | Custom error UI |
⚙️ Configuration
Default Configuration
{
enableRenderErrors: true, // Catch React render errors
enableSyncErrors: true, // Catch synchronous JS errors
enableAsyncErrors: true, // Catch async/promise errors
suppressDefaultHandler: true // Suppress red screen in dev
}Full Configuration Example
<GlobalErrorBoundary
config={{
enableRenderErrors: true,
enableSyncErrors: true,
enableAsyncErrors: true,
suppressDefaultHandler: true
}}
onError={(error, errorType, errorInfo) => {
// Your error handling logic
if (__DEV__) {
console.log(error);
} else {
// Send to Sentry, Firebase, etc.
yourErrorService.report(error);
}
}}
>
<App />
</GlobalErrorBoundary>🎨 Custom Fallback UI
Provide your own error screen:
import { FallbackComponentProps } from 'react-native-comprehensive-error-handler';
function CustomErrorScreen({ error, errorType, errorInfo, resetError }: FallbackComponentProps) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Oops! Something went wrong</Text>
<Text>{error.message}</Text>
<Button title="Try Again" onPress={resetError} />
</View>
);
}
<GlobalErrorBoundary fallbackComponent={CustomErrorScreen}>
<App />
</GlobalErrorBoundary>🔄 Programmatic Error Reset
Use a ref to reset errors programmatically:
import { useRef } from 'react';
import { GlobalErrorBoundary, GlobalErrorBoundaryRef } from 'react-native-comprehensive-error-handler';
function App() {
const errorBoundaryRef = useRef<GlobalErrorBoundaryRef>(null);
const handleReset = () => {
errorBoundaryRef.current?.resetError();
};
const checkError = () => {
const currentError = errorBoundaryRef.current?.getCurrentError();
if (currentError) {
console.log('Current error:', currentError);
}
};
return (
<GlobalErrorBoundary ref={errorBoundaryRef}>
<App />
</GlobalErrorBoundary>
);
}🧪 Testing
Test different error types to verify error handling:
// Render error
const ThrowRenderError = () => {
throw new Error('Test render error');
return null;
};
// Sync error
const throwSyncError = () => {
throw new Error('Test sync error');
};
// Async error
const throwAsyncError = async () => {
await Promise.reject(new Error('Test async error'));
};🌐 Platform Support
| Platform | Render Errors | Sync Errors | Async Errors | |----------|---------------|-------------|--------------| | iOS (Hermes) | ✅ | ✅ | ✅ | | iOS (JSC) | ✅ | ✅ | ✅ | | Android (Hermes) | ✅ | ✅ | ✅ | | Android (JSC) | ✅ | ✅ | ✅ | | Web | ✅ | ⚠️* | ✅ | | Expo | ✅ | ✅ | ✅ |
*Web sync errors are logged but may not trigger fallback UI due to browser behavior.
📝 TypeScript Support
Full TypeScript definitions included:
import {
GlobalErrorBoundary,
GlobalErrorBoundaryProps,
GlobalErrorBoundaryConfig,
GlobalErrorBoundaryRef,
FallbackComponentProps,
ErrorType,
ErrorState,
JSEngine,
} from 'react-native-comprehensive-error-handler';🔧 How It Works
Architecture
┌────────────────────────────────────────────┐
│ GlobalErrorBoundary │
└───────┬──────────────┬─────────────┬───────┘
│ │ │
┌────▼────┐ ┌────▼───┐ ┌────▼────────┐
│ Render │ │ Sync │ │ Async │
│ Error │ │ Error │ │ Error │
└────┬────┘ └───┬────┘ └────┬────────┘
│ │ │
┌────▼────────┐ ┌──▼─────────┐ ┌──▼───────────┐
│ React │ │ ErrorUtils │ │ Promise │
│ Boundary │ │ │ │ Tracker │
│ │ │ │ │(Multi-Engine)│
└─────────────┘ └────────────┘ └──────────────┘Engine Detection
Automatically detects and uses the appropriate promise rejection tracking:
- Hermes:
HermesInternal.enablePromiseRejectionTracker - JSC:
promise/setimmediate/rejection-trackingmodule - Web:
window.unhandledrejectionevent
🤔 FAQ
Q: Do I need to eject from Expo?
A: No! This package works perfectly with Expo without any configuration.
Q: Will this catch native errors?
A: No, this only catches JavaScript errors. Native crashes require platform-specific crash reporting tools.
Q: What's the performance impact?
A: Minimal. Error handlers are lightweight and only active when errors occur.
Q: Can I disable specific error types?
A: Yes! Use the config prop to disable any error type you don't want to catch.
Q: Can I ignore specific errors?
A: Yes! Simply check the error in your onError callback and decide whether to report it or not. You can also call resetError() immediately for errors you want to dismiss.
📚 Related Resources
🤝 Contributing
Contributions are welcome! Please open an issue or submit a pull request.
📄 License
MIT © Vikas Reddy
Made with ❤️ for the React Native community
