I am trying to create global handler for react native plugin, or at least in the application level, in TypeScript to catch all unhandled exceptions and log them.
I’m using react native 0.74.x version.
I found package react-native-exception-handler. But this was last updated 3 years ago, and is not maintained anymore.
I also found concept of Error Boundaries, but it looks like this solution doesn’t work for me.
ErrorBoundary class
import React, { Component, type ErrorInfo } from 'react';
import { Text } from 'react-native';
interface Props {
children: React.ReactNode;
}
interface State {
hasError: boolean;
}
class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
public static getDerivedStateFromError(_: Error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
console.error('ErrorBoundary caught an error: ', error, errorInfo);
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return <Text>Something went wrong.</Text>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Then I use this class on the following way:
const ExceptionTrackingView = () => {
return (
<ErrorBoundary>
<View>
<CustomButton
buttonTitle={item.key}
buttonOnPress={() => {
JSON.parse('Invalid JSON String');
}}
/>
</View>
</ErrorBoundary>
);
};
So in the button click event, it should create exception when trying to parse invalid JSON, and after that to console log error, from ErrorBoundary, but it gets never called.
Also, based on documentation, ErrorBoundary can’t catch the following errors:
- Event handlers (learn more)
- Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
- Server side rendering
- Errors thrown in the error boundary itself (rather than its children)
so, even if it works for the upper scenario, it doesn’t work for all errors.
Is there any package or solution to implement a global error handler for react-native applications to work with the latest react native version(s) 0.74.x and up?
2
Answers
Have you check the React Native global error handler?
You can import it from
import { ErrorUtils } from 'react-native';
and then in your application entry point config itThis will catch all unhandled exceptions in your React Native application.
Sentry is my favourite. But there are plenty of alternatives.
I would not recommend Bugsnag because of it badly handles unhandled issues.