Skip to main content

Error Handling

Graceful error recovery and fallback UI components

Error Handling

Proper error handling ensures your application remains functional and user-friendly even when things go wrong. Use error boundaries and fallback components to catch and display errors gracefully.

Common Error States

Different error scenarios and their presentations

Network Error
Connection failures with retry action
<ErrorFallback error={error} resetError={fn} />
Not Found (404)
Resource not found error
<ErrorFallback error={error} />
Access Denied (403)
Permission error with action
<ErrorFallback error={error} resetError={fn} />
With Stack Trace
Detailed error information
<ErrorFallback error={error} showDetails={true} />

Error Types

Network Errors

Failed API calls, connection timeouts, and offline states.

Validation Errors

Invalid form data, business logic violations, and constraint failures.

Authentication Errors

Expired sessions, invalid credentials, and permission denials.

Server Errors

500 errors, database failures, and service unavailability.

Implementation

Error Fallback Component

The ErrorFallback component provides a consistent error display:

<ErrorFallback
	error={error}
	resetError={() => handleRetry()}
	showDetails={isDevelopment}
	size="md"
/>

Error Boundary

Wrap components that might fail with an error boundary:

<ErrorBoundary>
	<RiskyComponent />
	{#snippet fallback(error, reset)}
		<ErrorFallback {error} resetError={reset} />
	{/snippet}
</ErrorBoundary>

Component Props

ErrorFallback Props

  • error: Error - The error object to display
  • resetError?: () => void - Optional recovery function
  • showDetails?: boolean - Show stack trace (dev mode only)
  • size?: 'sm' | 'md' | 'lg' - Component size variant

Size Variants

Small (sm) - For inline errors within forms or cards Medium (md) - Default size for section-level errors Large (lg) - Full-page error states

Best Practices

User Communication

  1. Clear messaging - Explain what went wrong in simple terms
  2. Actionable solutions - Provide steps to resolve the issue
  3. Recovery options - Include retry or alternative actions
  4. Contact support - Offer help for persistent issues

Technical Implementation

  1. Log errors - Send to monitoring service for debugging
  2. Graceful degradation - Maintain core functionality
  3. Retry logic - Implement exponential backoff
  4. Error boundaries - Contain failures to components

Error Messages

Good Examples

  • ✅ “Unable to load your profile. Please check your connection and try again.”
  • ✅ “This page couldn’t be found. Try searching or return home.”
  • ✅ “Your session has expired. Please log in again to continue.”

Poor Examples

  • ❌ “Error: ECONNREFUSED”
  • ❌ “Something went wrong”
  • ❌ “404”

Error Recovery Patterns

Automatic Retry

async function fetchWithRetry(url, attempts = 3) {
	for (let i = 0; i < attempts; i++) {
		try {
			return await fetch(url);
		} catch (error) {
			if (i === attempts - 1) throw error;
			await new Promise(r => setTimeout(r, 2 ** i * 1000));
		}
	}
}

Manual Recovery

<script>
let error = $state(null);
let isRetrying = $state(false);

async function retry() {
	isRetrying = true;
	error = null;
	try {
		await loadData();
	} catch (e) {
		error = e;
	} finally {
		isRetrying = false;
	}
}
</script>

{#if error}
	<ErrorFallback {error} resetError={retry} />
{/if}

Fallback Content

{#await loadData()}
	<Spinner />
{:then data}
	<DataDisplay {data} />
{:catch error}
	<ErrorFallback {error}>
		<!-- Show cached or default content -->
		<StaticContent />
	</ErrorFallback>
{/await}

Accessibility

Error states must be accessible to all users:

  • Use role="alert" for critical errors
  • Include aria-live regions for dynamic updates
  • Provide keyboard-accessible recovery actions
  • Ensure sufficient color contrast for error text
  • Don’t rely solely on color to indicate errors

Error Monitoring

Track and analyze errors in production:

window.addEventListener('error', (event) => {
	// Send to monitoring service
	logError({
		message: event.message,
		source: event.filename,
		line: event.lineno,
		column: event.colno,
		stack: event.error?.stack
	});
});

Testing Error States

Always test error handling:

  1. Network failures - Test offline and slow connections
  2. Invalid data - Submit malformed requests
  3. Permission errors - Test with different user roles
  4. Server errors - Mock 500 responses
  5. Edge cases - Test boundary conditions