Blog>
Snippets

Custom Error Handling on Route Change

Explain how to handle route change errors with a custom error boundary interceptor to display error-specific user feedback or logging.
class RouteChangeErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true, error: error };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <div>An error occurred: {this.state.error.message}</div>;
    }
    return this.props.children;
  }
}
// This is a React component that acts as an error boundary. When a route change error occurs, it will catch the error and update the state to display a fallback UI with an error message.
function logErrorToMyService(error, errorInfo) {
  // Implement error logging logic
  console.error('Logging error:', error, errorInfo);
}
// This is a function to log errors to a service or console. Replace the console.error with the actual error logging implementation.
function App() {
  return (
    <Router>
      <RouteChangeErrorBoundary>
        <Switch>
          {/* Define your route components here */}
          <Route path='/some-path' component={SomeComponent} />
          {/* Other routes */}
        </Switch>
      </RouteChangeErrorBoundary>
    </Router>
  );
}
// This is the main component that uses the RouteChangeErrorBoundary. It should wrap the routing logic to catch and handle errors during route changes.