Error handling

Learn how to handle navigation errors, implement error recovery patterns, and create robust routing experiences.

Navigation errors are inevitable in complex applications. The Aurelia router provides comprehensive error handling mechanisms to help you create resilient routing experiences. This section covers error types, recovery patterns, and best practices for handling routing failures.

Types of Router Errors

Errors that occur during the navigation process:

import { IRouterEvents, NavigationErrorEvent } from '@aurelia/router';
import { resolve } from '@aurelia/kernel';

export class ErrorHandler {
  private routerEvents = resolve(IRouterEvents);

  attached() {
    this.routerEvents.subscribe('au:router:navigation-error', (event: NavigationErrorEvent) => {
      console.error('Navigation failed:', event.error);
      console.log('Failed instructions:', event.instructions);
      console.log('Navigation ID:', event.id);
      
      this.handleNavigationError(event.error);
    });
  }

  private handleNavigationError(error: unknown) {
    if (error instanceof Error) {
      // Handle specific error types
      switch (error.name) {
        case 'UnknownRouteError':
          this.router.load('not-found');
          break;
        case 'NetworkError':
          this.showRetryDialog();
          break;
        default:
          this.showGenericError(error.message);
      }
    }
  }
}

Component Loading Errors

Errors that occur when loading route components:

Hook Validation Errors

Errors thrown by lifecycle hooks:

Error Recovery Configuration

Automatic Route Tree Restoration

Configure the router to automatically restore the previous route tree on errors:

With this setting enabled (default), navigation failures automatically restore the previous working route state:

Strict Error Handling

For applications requiring stricter error handling, disable automatic restoration:

In strict mode, handle errors explicitly:

Error Handling Patterns

Global Error Boundary

Create a global error boundary for routing errors:

Component-Level Error Handling

Handle errors at the component level for fine-grained control:

Fallback Routes and Components

Configure fallback handling for unknown routes:

Error Recovery Strategies

Retry with Exponential Backoff

Implement retry logic for transient errors:

Graceful Degradation

Provide fallback experiences when navigation fails:

Error Monitoring and Logging

Comprehensive Error Tracking

Best Practices

1. Always Handle Navigation Errors

2. Provide User Feedback

3. Use Appropriate Error Recovery

This comprehensive error handling documentation fills a significant gap by providing developers with patterns and strategies for creating robust routing experiences.

Last updated

Was this helpful?