Error Handling in Async Dioxus
Dioxus provides powerful error handling mechanisms that make it easy to catch, display, and recover from errors in your application.ErrorBoundary Component
TheErrorBoundary component catches errors from child components and renders a custom error UI:
How It Works
Dioxus automatically catches errors from:- Rendering - Errors returned from component functions
- Event handlers - Errors returned from event handlers
- Async operations - Errors from futures and resources
- Panics - Panics in components (except in WASM)
Returning Errors
Components and handlers can returnResult<Element, E> where E implements Into<anyhow::Error>:
Event Handler Errors
Event handlers can returnResult<(), Error>:
The bail! Macro
Use the bail! macro to return early with an error:
ErrorContext API
TheErrorContext provides information about caught errors:
Methods
error()- Get the current error (returnsOption<CapturedError>)clear_errors()- Clear all errors and retry rendering
Resetting Error Boundaries
You can clear errors and retry rendering:Error Type Checking
You can downcast errors to specific types for custom handling:Multiple Error Types
Iterate over all errors:Catching Panics
On desktop platforms, Dioxus catches panics automatically:Async Error Handling
With use_resource
With Suspense
CombineErrorBoundary with SuspenseBoundary:
Error Propagation
Errors bubble up to the nearest error boundary:Nested Error Boundaries
Use multiple boundaries for granular error handling:Custom Error Types
Create custom error types for your application:Best Practices
1. Use Specific Error Types
Define clear error types for different parts of your app:2. Provide Context
Add context to errors for better debugging:3. User-Friendly Error Messages
Show helpful messages to users:4. Log Errors
Log errors for monitoring:5. Granular Boundaries
Use multiple boundaries to isolate failures:Complete Example
Here’s a complete example showing error handling with async data:Next Steps
- Learn about Suspense boundaries for loading states
- Understand use_resource for data fetching
- See Futures for background tasks