Now.js Framework Documentation
AuthErrorHandler - Error Management for Authentication
AuthErrorHandler - Error Management for Authentication
Documentation for AuthErrorHandler, the error management system for authentication in the Now.js Framework
📋 Table of Contents
- Overview
- Installation and Import
- Getting Started
- Error Types
- Error Actions
- Error Events
- API Reference
- Best Practices
- Common Pitfalls
Overview
AuthErrorHandler manages errors and exceptions that occur during the authentication process, providing appropriate responses and recovery mechanisms.
Key Features
- ✅ Error Classification: Clear categorization of errors
- ✅ Configurable Actions: Define actions for each error type
- ✅ Custom Handlers: Support for custom error handlers
- ✅ Retry Logic: Automatic retry for specific error types
- ✅ Error Recovery: Recovery mechanisms from errors
- ✅ Event System: Events for error tracking
- ✅ User Notifications: Notify users when errors occur
- ✅ Error Logging: Record errors for debugging
- ✅ Graceful Degradation: Gracefully degrade features
- ✅ Error Boundaries: Limit the scope of errors
When to Use AuthErrorHandler
✅ Use AuthErrorHandler when:
- Need systematic authentication error management
- Want custom error handling logic
- Need to track and log errors
- Want retry logic for errors
- Need to notify users when errors occur
❌ Don't use when:
- Need to handle all errors manually
- Not using authentication system
Installation and Import
AuthErrorHandler is loaded with the Now.js Framework and is ready to use immediately via the window object:
// No import needed - ready to use immediately
console.log(window.AuthErrorHandler); // AuthErrorHandler objectGetting Started
Basic Setup
// AuthErrorHandler works automatically with AuthManager
// No separate initialization needed
await AuthManager.init({
enabled: true,
endpoints: {
login: '/api/auth/login',
verify: '/api/auth/verify'
},
// Error handling configuration
errorHandling: {
// Max retry attempts
maxRetries: 3,
// Retry delay (ms)
retryDelay: 1000,
// Show user notifications
showNotifications: true,
// Log errors to console
logErrors: true
}
});
console.log('AuthErrorHandler initialized with AuthManager');Error Handling Flow
Operation fails
↓
┌────────────────────┐
│ Classify Error │
│ - Network? │
│ - Authentication? │
│ - Authorization? │
│ - Validation? │
└──────┬─────────────┘
↓
┌────────────────────┐
│ Determine Action │
│ - Retry? │
│ - Redirect? │
│ - Notify? │
│ - Log? │
└──────┬─────────────┘
↓
┌────────────────────┐
│ Execute Action │
│ - Retry operation │
│ - Navigate away │
│ - Show message │
│ - Log error │
└──────┬─────────────┘
↓
┌────────────────────┐
│ Emit Error Event │
│ - Custom handlers │
│ - Tracking │
│ - Logging │
└────────────────────┘Error Types
AuthErrorHandler supports the following main error types:
1. NETWORK_ERROR
Connection or network failure
// Triggered when:
// - No internet connection
// - Server unreachable
// - Request timeout
// - CORS errors
// Default action: Retry with exponential backoff
{
type: 'NETWORK_ERROR',
message: 'Network connection failed',
retryable: true,
action: 'retry'
}2. UNAUTHORIZED
Not authenticated or token expired
// Triggered when:
// - No token provided
// - Token expired
// - Invalid token
// - Token revoked
// Default action: Redirect to login
{
type: 'UNAUTHORIZED',
message: 'Authentication required',
retryable: false,
action: 'redirect',
target: '/login'
}3. FORBIDDEN
Authenticated but no permission
// Triggered when:
// - Missing required role
// - Missing required permission
// - Access denied by policy
// Default action: Show error page
{
type: 'FORBIDDEN',
message: 'Access denied',
retryable: false,
action: 'render',
target: '/403'
}4. VALIDATION_ERROR
Data does not meet requirements
// Triggered when:
// - Invalid credentials
// - Missing required fields
// - Invalid format
// Default action: Show validation errors
{
type: 'VALIDATION_ERROR',
message: 'Invalid input',
errors: {
email: 'Invalid email format',
password: 'Password too short'
},
retryable: true,
action: 'notify'
}5. TOKEN_EXPIRED
Token has expired
// Triggered when:
// - Access token expired
// - Refresh token expired
// Default action: Try refresh, then redirect
{
type: 'TOKEN_EXPIRED',
message: 'Token expired',
retryable: true,
action: 'refresh',
fallback: 'redirect',
target: '/login'
}6. TOKEN_REFRESH_FAILED
Token refresh failed
// Triggered when:
// - Refresh token invalid
// - Refresh endpoint failed
// - No refresh token
// Default action: Redirect to login
{
type: 'TOKEN_REFRESH_FAILED',
message: 'Failed to refresh token',
retryable: false,
action: 'redirect',
target: '/login'
}7. SESSION_EXPIRED
Session has expired
// Triggered when:
// - Session timeout
// - Session invalidated
// - Logged out from another device
// Default action: Redirect to login with message
{
type: 'SESSION_EXPIRED',
message: 'Your session has expired',
retryable: false,
action: 'redirect',
target: '/login',
notify: true
}8. RATE_LIMIT_EXCEEDED
Rate limit exceeded
// Triggered when:
// - Too many requests
// - Rate limit exceeded
// Default action: Retry after delay
{
type: 'RATE_LIMIT_EXCEEDED',
message: 'Too many requests',
retryable: true,
action: 'retry',
retryAfter: 60000, // 1 minute
notify: true
}9. SERVER_ERROR
Internal server error
// Triggered when:
// - 500 errors
// - Server exceptions
// - Database errors
// Default action: Retry with limit
{
type: 'SERVER_ERROR',
message: 'Server error occurred',
retryable: true,
action: 'retry',
maxRetries: 3
}10. CSRF_ERROR
CSRF token invalid
// Triggered when:
// - CSRF token missing
// - CSRF token invalid
// - CSRF token expired
// Default action: Refresh CSRF and retry
{
type: 'CSRF_ERROR',
message: 'CSRF validation failed',
retryable: true,
action: 'refresh_csrf',
fallback: 'reload'
}11. CUSTOM_ERROR
Custom application-defined error
// Triggered by application logic
{
type: 'CUSTOM_ERROR',
code: 'SUBSCRIPTION_REQUIRED',
message: 'Active subscription required',
retryable: false,
action: 'custom',
handler: 'handleSubscriptionError'
}Error Actions
1. Retry Action
// Automatically retry failed operation
{
action: 'retry',
maxRetries: 3,
retryDelay: 1000,
backoff: 'exponential' // linear, exponential, fixed
}
// Retry with exponential backoff
// Attempt 1: 1s delay
// Attempt 2: 2s delay
// Attempt 3: 4s delay2. Redirect Action
// Redirect to another route
{
action: 'redirect',
target: '/login',
reason: 'Authentication required',
storeIntendedRoute: true // Store current route
}
// After login, redirect back to intended route3. Render Action
// Render error page
{
action: 'render',
target: '/403',
context: {
error: 'Access denied',
requiredRole: 'admin'
}
}4. Notify Action
// Show notification to user
{
action: 'notify',
notification: {
type: 'error',
title: 'Login Failed',
message: 'Invalid credentials',
duration: 5000
}
}5. Block Action
// Block navigation, stay on current page
{
action: 'block',
reason: 'Unsaved changes',
confirm: true // Show confirmation dialog
}6. Refresh Action
// Refresh tokens
{
action: 'refresh',
type: 'token',
fallback: {
action: 'redirect',
target: '/login'
}
}7. Logout Action
// Force logout
{
action: 'logout',
reason: 'Session invalidated',
redirect: '/login',
notify: true
}8. Custom Action
// Execute custom handler
{
action: 'custom',
handler: async (error, context) => {
console.log('Custom error handler:', error);
// Custom logic
if (error.code === 'PAYMENT_REQUIRED') {
await showPaymentModal();
}
return { handled: true };
}
}Error Events
AuthErrorHandler emits a single event through EventManager and puts the error
type in the payload — there is no separate event per error type.
| Event | When Triggered | Detail |
|---|---|---|
auth:error |
An auth error was handled | {errorInfo, config, context, timestamp} |
EventManager.on('auth:error', ({errorInfo, context}) => {
// Branch on errorInfo.type instead of listening for many events
switch (errorInfo.type) {
case 'unauthorized':
console.log('User unauthorized');
break;
case 'network':
showOfflineIndicator();
break;
default:
console.log('Auth error:', errorInfo.type, context);
}
});API Reference
Methods
handleError(error, context)
Handle an error with configured actions
Parameters:
error(Object/Error) - Error objectcontext(Object) - Error context
Returns: Promise<Object> - Handling result
Example:
try {
await AuthManager.login(credentials);
} catch (error) {
await AuthErrorHandler.handleError(error, {
operation: 'login',
route: Router.getCurrentRoute()
});
}Best Practices
1. Handle Errors Gracefully
// ✅ Good - graceful error handling
try {
await AuthManager.login(credentials);
} catch (error) {
// Error automatically handled by AuthErrorHandler
console.log('Login failed, error handled');
}
// ❌ Bad - no error handling
await AuthManager.login(credentials); // Uncaught errors!2. Provide User Feedback
// ✅ Good - clear user feedback
EventManager.on('auth:error', ({errorInfo}) => {
if (errorInfo.type !== 'validation') return;
showValidationErrors(errorInfo.errors);
showNotification('Please fix the errors and try again', 'error');
});
// ❌ Bad - silent failures
// User doesn't know what went wrong3. Log Errors Appropriately
// ✅ Good - structured error logging
EventManager.on('auth:error', (e) => {
const { error, context } = e.detail;
logger.error({
type: error.type,
message: error.message,
context: context,
timestamp: new Date().toISOString()
});
});
// ❌ Bad - no logging
// Cannot debug production issues4. Implement Retry with Limits
// ✅ Good - retry with exponential backoff and limit
{
maxRetries: 3,
retryBackoff: 'exponential',
retryDelay: 1000
}
// ❌ Bad - unlimited retries
{
maxRetries: Infinity // Never stops trying!
}Common Pitfalls
1. Not Handling All Error Types
// ❌ Bad - only handles unauthorized
EventManager.on('auth:error', ({errorInfo}) => {
if (errorInfo.type === 'unauthorized') redirectToLogin();
});
// What about network errors? Validation errors?
// ✅ Good - handle all error types
EventManager.on('auth:error', (e) => {
const { error } = e.detail;
switch (error.type) {
case 'UNAUTHORIZED':
redirectToLogin();
break;
case 'NETWORK_ERROR':
showOfflineMode();
break;
case 'VALIDATION_ERROR':
showValidationErrors(error.errors);
break;
default:
showGenericError(error.message);
}
});2. Swallowing Errors
// ❌ Bad - error disappears
try {
await AuthManager.login(credentials);
} catch (error) {
// Do nothing - error is lost
}
// ✅ Good - at least log the error
try {
await AuthManager.login(credentials);
} catch (error) {
console.error('Login failed:', error);
// Let AuthErrorHandler handle it
throw error;
}3. Retry Without Backoff
// ❌ Bad - retry immediately forever
{
retryBackoff: 'fixed',
retryDelay: 0,
maxRetries: 999
}
// This hammers the server!
// ✅ Good - exponential backoff with limit
{
retryBackoff: 'exponential',
retryDelay: 1000,
maxRetries: 3
}Related Documentation
- Authentication.md - Authentication system overview
- AuthManager.md - Core authentication manager
- AuthGuard.md - Route protection
- TokenService.md - JWT token management
- AuthLoadingManager.md - Loading states