🚨 Error Handling
Comprehensive error handling with onError hook, error mapping, and custom error modification.
Z-Fetch provides comprehensive error handling capabilities that intercept all error types and allow you to customize error messages and behavior throughout your application.
Error Types Covered
The error handling system captures:
- HTTP errors (4xx/5xx status codes)
- Network errors (connection failures, DNS issues)
- Timeout errors (request timeouts → status:
TIMEOUT, message:"Request timed out!") - Cancellation (user-initiated abort → status:
CANCELED, message:"Request canceled") - Parse errors (invalid JSON responses)
- Request errors (malformed requests)
Complete Coverage
The onError hook provides comprehensive error coverage and modification capabilities for better user experience.
Cancellation and Timeout
Z-Fetch standardizes cancellation and timeouts across both fetch and XHR paths:
- Cancellation (manual abort) yields
error.status = 'CANCELED'anderror.message = 'Request canceled'. - Timeout (exceeding configured
timeout) yieldserror.status = 'TIMEOUT'anderror.message = 'Request timed out!'. - Error mapping does not override cancel/timeout messages by default.
onError Hook
The onError hook intercepts all errors and allows you to modify them:
Error Context
The onError hook receives a comprehensive context object:
Error Modification
Using setError Helper
Using Return Values
Error Mapping
Define custom error messages for common error patterns:
Pattern Matching
Error mapping supports flexible pattern matching:
Real-World Examples
Authentication Error Handling
Retry Logic with Error Handling
User-Friendly Error Messages
Error Logging and Tracking
Integration with Error Mapping
The onError hook works alongside error mapping:
Error Recovery Patterns
Fallback Data
Graceful Degradation
Error Hook Best Practices
Comprehensive Logging: Always log errors for debugging User-Friendly Messages: Provide clear, actionable error messages Error Classification: Categorize errors for better handling Context Preservation: Keep original error information Recovery Options: Provide fallback data when possible Security: Don't expose sensitive error details to users
Related Features
Error handling works seamlessly with other Z-Fetch features:
- 🟡 Streaming Support - Comprehensive error handling for streaming operations
- ⭐ Progress Tracking - Error handling for upload/download operations
- 💪 Using Hooks - Enhanced hooks system with onError hook for request lifecycle management
- 👉 Request Methods - All HTTP methods support comprehensive error handling