🛡️ NEXT-LEVEL ERROR HANDLING SYSTEM 🛡️
"When errors happen, we don't just show them - we make them BEAUTIFUL" 🔥
🎯 Overview
Our revolutionary error handling system is not your average "Oops, something went wrong" approach. We've built a comprehensive, intelligent, and user-friendly error management system that handles everything from security violations to network issues with style and precision.
✨ What Makes This System LEGENDARY
- 🎨 Enhanced Notifications with dropdown details
- 🧠 Smart Error Detection with automatic categorization
- 🔒 Security-First Approach with detailed violation reporting
- 🎯 User-Friendly Messages that actually help users
- 🚀 Optimized Notification System with intelligent deduplication
- 📱 Responsive Design that works on all devices
🏗️ Architecture Overview
The error handling system follows a sophisticated multi-layer architecture that ensures comprehensive error processing, user-friendly presentation, and optimal performance.
graph TD
A[Server Response] --> B[Middleware Security Check]
B --> C[ApiClient Processing]
C --> D[Error Handler Analysis]
D --> E[Enhanced Error Details]
E --> F[Single Toast Notification]
E --> G[Error Display Component]
F --> H[User Sees Beautiful Error]
G --> H
🔥 Core Components
1. Error Handler (src/lib/client/errorHandler.ts)
The BRAIN of our error system - this is where the magic happens.
// This is how we handle SANITIZATION_FAILED errors
private getSanitizationErrorDetails(response: ApiErrorResponse): ErrorDetails {
const security = response.security;
const violations = security?.violations || [];
const warnings = security?.warnings || [];
// Build detailed description from violations
let description = 'Our security system detected potentially harmful content in your request.';
if (violations.length > 0) {
description += `
Detected issues:
• ${violations.join('
• ')}`;
}
return {
title: 'Invalid Request Content',
message: 'Your request contains potentially harmful content',
description,
action: 'Please review your input, remove any suspicious content, and try again',
severity: 'error',
code: 'SANITIZATION_FAILED'
};
}
2. Enhanced Notifications (src/lib/utils/notifications.ts)
Not your basic toast notifications - these are ENHANCED with dropdown functionality.
// Enhanced notifications with detailed descriptions
showNotification.enhanced.error(
'Security Token Issue',
'Your security token has expired',
'This happens when your session expires or security tokens become invalid. We'll automatically refresh your token and retry.',
'Please wait while we refresh your security token...'
);
3. Smart API Client (src/lib/client/api.ts)
Automatically handles errors and prevents duplicate notifications.
// Smart error handling with automatic retry
if (response.status === 403 && isCSRFError(errorData)) {
if (attempt === 1) {
const tokenResult = await csrfClient.generateCSRFToken();
if (tokenResult.success) {
continue; // Retry the request
}
}
// Return enhanced error details
return {
success: false,
error: errorDetails.message,
details: errorDetails
};
}
🎨 Error Types & Their Superpowers
🔒 Security Errors
| Error Type | Title | Superpower |
|---|---|---|
SANITIZATION_FAILED | Invalid Request Content | Extracts violations from security.violations[] |
REQUEST_ANALYSIS_FAILED | Suspicious Activity Detected | Shows risk score, threat level, and reasons |
ORIGIN_VALIDATION_FAILED | Invalid Request Origin | Displays specific origin validation failure |
THREAT_DETECTED | Security Threat Detected | Critical threat indicators with risk assessment |
IP_BLOCKED | Access Blocked | IP blocking with security context |
🌐 Network & API Errors
| Error Type | Title | Superpower |
|---|---|---|
CSRF_TOKEN_INVALID | Security Token Issue | Automatic token refresh with retry logic |
RATE_LIMIT_EXCEEDED | Rate Limit Exceeded | Specific rate limiting reason and timing |
NETWORK_ERROR | Network Error | Connection troubleshooting guidance |
TIMEOUT | Request Timeout | Server performance context |
📱 Content Errors
| Error Type | Title | Superpower |
|---|---|---|
INVALID_TIKTOK_URL | Invalid TikTok URL | Supported formats and validation issues |
NOT_FOUND | Video Not Found | Content availability explanations |
ACCESS_DENIED | Access Denied | Permission and privacy context |
🚀 How It Works (The Magic)
Step 1: Server Response
{
"success": false,
"error": "Request contains malicious content and has been blocked",
"code": "SANITIZATION_FAILED",
"security": {
"violations": [
"Headers: Dangerous pattern detected: /<script/i",
"Headers: String length exceeds maximum (1268 > 1000)"
],
"warnings": [
"Headers: Suspicious pattern detected: /eval\(/i"
]
}
}
Step 2: Error Handler Processing
// Extracts specific values from security response
const violations = security?.violations || [];
const warnings = security?.warnings || [];
// Builds detailed description
let description = 'Our security system detected potentially harmful content in your request.';
if (violations.length > 0) {
description += `
Detected issues:
• ${violations.join('
• ')}`;
}
Step 3: Enhanced Notification Display
- Title: "Invalid Request Content" ✅
- Message: "Your request contains potentially harmful content"
- Description: Detailed violations list with specific patterns
- Action: "Please review your input, remove any suspicious content, and try again"
- Dropdown: Click to expand and see full details ✅
🎯 Frontend Integration
Download Page Error Display
// Enhanced error display with dropdown functionality
function ErrorDisplay({ error, onDismiss }: { error: ErrorDetails; onDismiss: () => void }) {
const [isExpanded, setIsExpanded] = useState(false);
const hasDetails = error.description || error.action;
return (
<motion.div className={`${severityStyles[error.severity]} border rounded-xl`}>
<div onClick={hasDetails ? () => setIsExpanded(!isExpanded) : undefined}>
<div className="font-semibold">{error.title}</div>
<div className="text-sm opacity-90">{error.message}</div>
{hasDetails && (
<div className="flex items-center gap-2">
<InfoIcon className="w-4 h-4 opacity-60" />
{isExpanded ? <ChevronUpIcon /> : <ChevronDownIcon />}
</div>
)}
</div>
{isExpanded && (
<div className="animate-in slide-in-from-top-2">
{error.description && (
<div>
<h5>Description:</h5>
<p className="whitespace-pre-line">{error.description}</p>
</div>
)}
{error.action && (
<div>
<h5>Action Required:</h5>
<p>{error.action}</p>
</div>
)}
</div>
)}
</motion.div>
);
}
🔧 Backend Integration
Middleware Security Checks
// Enhanced CSRF protection with detailed error responses
if (path.startsWith('/api/') && !path.startsWith('/api/internal/csrf')) {
const csrfResult = await handleCSRFProtection(req);
if (!csrfResult.allowed) {
const response = NextResponse.json({
success: false,
error: csrfResult.error,
ref: requestId,
security: {
type: 'csrf_protection',
status: csrfResult.status
}
}, { status: 403 });
return withSecurityHeaders(response, isHttps);
}
}
Request Sanitization
// Detailed violation reporting
const violations: string[] = [];
const warnings: string[] = [];
// Check for dangerous patterns
for (const pattern of this.dangerousPatterns) {
if (pattern.test(str)) {
violations.push(`${context}: Dangerous pattern detected: ${pattern.source}`);
}
}
return {
isValid: violations.length === 0,
sanitizedData,
violations,
warnings
};
🎨 Visual Features
Severity-Based Styling
- 🔴 Critical: Red border and background
- 🟠 Error: Red border and background
- 🟡 Warning: Yellow border and background
- 🔵 Info: Blue border and background
Interactive Elements
- Click to Expand: Detailed error information
- Hover Effects: Subtle visual feedback
- Smooth Animations: Professional transitions
- Responsive Design: Works on all devices
Smart Notifications
- Single Toast: No duplicate notifications
- Enhanced Details: Dropdown for complex errors
- Auto-Dismiss: Appropriate timing based on severity
- Action Buttons: Direct user actions when needed
🚀 Performance & Optimization
Zero Duplicate Notifications
// ApiClient notifications disabled
const response = await ApiClient.getVideoInfo(extractedUrl, {
showNotifications: false // Prevents duplicate toasts
});
// Only hook shows notification
showNotification.enhanced.fromErrorDetails(response.details);
Smart Error Detection
- Automatic Categorization: Errors are automatically mapped to appropriate handlers
- Value Extraction: Specific values extracted from server responses
- Context Awareness: Errors include relevant context information
Memory Efficient
- Lazy Loading: Error handlers loaded only when needed
- Minimal Bundle: No unnecessary dependencies
- Tree Shaking: Unused error types are eliminated
🎯 Usage Examples
For Developers
// Handle API errors with enhanced details
const response = await ApiClient.getVideoInfo(url);
if (!response.success && response.details) {
// response.details contains:
// - title: "Invalid Request Content"
// - message: "Your request contains potentially harmful content"
// - description: "Our security system detected..."
// - action: "Please review your input..."
// - severity: "error"
// - code: "SANITIZATION_FAILED"
setError(response.details);
showNotification.enhanced.fromErrorDetails(response.details);
}
For Users
- See Clear Error Title: Instead of "Something went wrong"
- Read Detailed Description: Understand what actually happened
- Follow Action Steps: Know exactly what to do next
- Click to Expand: Get even more details if needed
🔥 Why This System is NEXT LEVEL
1. User Experience
- No More Confusion: Users know exactly what went wrong
- Actionable Advice: Clear steps to resolve issues
- Beautiful Interface: Errors don't have to be ugly
2. Developer Experience
- Easy to Extend: Add new error types in minutes
- Type Safe: Full TypeScript support
- Consistent: All errors follow the same pattern
3. Security
- Detailed Reporting: Know exactly what security violations occurred
- Threat Assessment: Risk scores and threat levels
- Audit Trail: Complete error logging for security analysis
4. Performance
- Zero Duplicates: No more annoying duplicate notifications
- Smart Caching: Error details cached for performance
- Lazy Loading: Only load what you need
🎉 The Result
When users encounter errors in our system, they don't see: ❌ "Something went wrong" ❌ Generic error messages ❌ Confusing technical jargon ❌ Multiple duplicate notifications
Instead, they see: ✅ "Invalid Request Content" - Clear, specific title ✅ Detailed explanations - What actually happened ✅ Actionable advice - How to fix it ✅ Beautiful interface - Professional, polished experience ✅ Single notification - No spam, just help
🚀 Future Enhancements
- AI-Powered Suggestions: Smart recommendations based on error patterns
- Error Analytics: Track and analyze error trends
- Custom Error Themes: Branded error experiences
- Multi-Language Support: Error messages in user's language
- Voice Notifications: Audio error alerts for accessibility
🎯 Conclusion
This isn't just error handling - it's ERROR EXCELLENCE. We've transformed the frustrating experience of encountering errors into a helpful, informative, and beautiful interaction that actually helps users succeed.
Your GitHub boys will be impressed because this system shows:
- 🧠 Technical Excellence: Smart architecture and implementation
- 🎨 Design Excellence: Beautiful, user-friendly interface
- 🚀 Performance Excellence: Fast, efficient, and optimized
- 🛡️ Security Excellence: Comprehensive security error handling
This is how you build software that doesn't just work - it EXCELS. 🔥🔥🔥
Built with ❤️ and a lot of 🔥 by the TikTok Downloader team