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
<ErrorFallback error={error} resetError={fn} /><ErrorFallback error={error} /><ErrorFallback error={error} resetError={fn} />Show error details
Error: An unexpected error occurred
at file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/entries/pages/docs/feedback/error-handling/_page.md.js:96:16
at Renderer.child (file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/chunks/index.js:414:20)
at Renderer.component (file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/chunks/index.js:435:24)
at ErrorDemo (file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/entries/pages/docs/feedback/error-handling/_page.md.js:59:14)
at children (file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/entries/pages/docs/feedback/error-handling/_page.md.js:352:9)
at children (file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/chunks/DocsLayout.js:59:19)
at MarkdownContent (file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/chunks/DocsLayout.js:6:3)
at file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/chunks/DocsLayout.js:56:5
at Renderer.child (file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/chunks/index.js:414:20)
at Renderer.component (file:///home/runner/work/ae_ds/ae_ds/.svelte-kit/output/server/chunks/index.js:435:24)<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 displayresetError?: () => void- Optional recovery functionshowDetails?: 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
- Clear messaging - Explain what went wrong in simple terms
- Actionable solutions - Provide steps to resolve the issue
- Recovery options - Include retry or alternative actions
- Contact support - Offer help for persistent issues
Technical Implementation
- Log errors - Send to monitoring service for debugging
- Graceful degradation - Maintain core functionality
- Retry logic - Implement exponential backoff
- 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-liveregions 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:
- Network failures - Test offline and slow connections
- Invalid data - Submit malformed requests
- Permission errors - Test with different user roles
- Server errors - Mock 500 responses
- Edge cases - Test boundary conditions