Error Handling Strategy
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
The MoodTune backend implements a multi-layered error handling strategy designed to ensure API stability and provide meaningful feedback to both the frontend and developers. The strategy encompasses HTTP-level exceptions for client responses, fallback mechanisms for audio processing failures, and integrated monitoring via Sentry for real-time error tracking and performance profiling.
The system distinguishes between user-facing errors (e.g., authentication failures, invalid inputs) and internal processing errors (e.g., Spotify API timeouts, audio analysis failures). While the API aims for "Async everywhere" to prevent blocking, it utilizes structured try-except blocks to catch I/O and processing exceptions, often returning default feature sets to ensure partial service availability in non-critical failure scenarios.
Sources: CLAUDE.md:65-72, IMPROVEMENTS.md:73-81, app/main.py:8-20
API Error Handling Architecture
The backend utilizes FastAPI's HTTPException for standardizing error responses. These exceptions are raised across routers and services to return appropriate HTTP status codes and descriptive detail messages to the client.
Standardized HTTP Responses
The project follows a pattern of raising specific status codes based on the failure type:
| Status Code | Scenario | Source File |
|---|---|---|
400 Bad Request | Invalid input, missing files, or insufficient track count | app/api/v1/song_analysis.py:112 |
401 Unauthorized | Invalid or expired Supabase JWT token | TEST_PLAN.md:66-72 |
403 Forbidden | Accessing resources belonging to another user | TEST_PLAN.md:83-85 |
404 Not Found | Missing Spotify connection, playlists, or analysis records | app/api/v1/song_analysis.py:89 |
413 Request Entity Too Large | Audio file upload exceeds MAX_UPLOAD_SIZE_MB | app/api/v1/song_analysis.py:126 |
500 Internal Server Error | Unexpected processing failures or service-level exceptions | app/api/v1/analysis.py:112 |
502 Bad Gateway | Failure in upstream services like Spotify or Jamendo | app/api/v1/song_analysis.py:98 |
Sources: app/api/v1/song_analysis.py:89-105, app/api/v1/analysis.py:110-116
API Error Flow
The following diagram illustrates the typical error flow when a user request fails validation or external service integration.
A flowchart showing the progression of checks (Auth, Resource, Logic) and the resulting error codes.
Sources: TEST_PLAN.md:60-120, app/api/v1/song_analysis.py:85-105
Audio Analysis Resilience
The AudioAnalysisService implements specific fallback logic to prevent the entire pipeline from failing when a single audio feature cannot be extracted.
Fallback Feature Sets
If an exception occurs during librosa processing (e.g., file corruption or decoding errors), the service returns a "default features" dictionary. This allows the API to return a successful response structure even if the data is estimated.
def _default_features(self) -> Dict:
"""Fallback if analysis fails"""
return {
"tempo": 120.0,
"energy": 0.5,
"valence": 0.5,
"danceability": 0.5,
"loudness": -10.0,
}
Sources: app/services/audio_analysis_service.py:241-250
Processing Cleanup
To prevent resource leaks during failed analyses, the service utilizes try...finally blocks to ensure temporary audio files are deleted regardless of whether the analysis succeeded or raised an exception.
Sources: app/services/audio_analysis_service.py:48-52, app/services/audio_analysis_service.py:100-104
Monitoring and Debugging
The backend integrates Sentry for error tracking and performance monitoring. This is configured globally in app/main.py and utilized granularly within services.
Sentry Integration
Sentry tracks exceptions, breadcrumbs, and transaction spans across the application:
- Initialization: Configured with
FastApiIntegrationandLoggingIntegration. - Transaction Spanning: Used in
AudioAnalysisServiceto measure specific spans likeaudio.load,audio.tempo, andaudio.features. - Contextual Data: Custom context is set for
audiometadata (sample rate, duration) andsong_requestdetails (track ID, name) to assist in debugging specific failures.
Sources: app/main.py:8-20, app/services/audio_analysis_service.py:59-70, app/api/v1/song_analysis.py:136-140
Error Reporting Sequence
The diagram below shows how an internal error is captured and reported while the client receives a structured response.
A sequence diagram showing how the AudioService captures an exception in Sentry but returns default features to maintain API responsiveness.
Sources: app/services/audio_analysis_service.py:88-92, app/api/v1/song_analysis.py:143-160
Implementation Deficiencies and Planned Improvements
The project documentation identifies several gaps in the current error handling strategy that are slated for future refinement.
- Granular Handling: The system currently returns default features on any error, which may mask legitimate infrastructure or connectivity problems.
- Input Validation: Lack of validation for preview URL formats and audio durations before processing.
- Partial Results: Plans to return partial results if only specific features (e.g., tempo) fail while others succeed.
Sources: IMPROVEMENTS.md:73-82
Summary
MoodTune's error handling strategy focuses on maintaining service availability through fallback data and providing detailed monitoring for developers via Sentry. While client-facing errors are standardized using FastAPI's HTTPException, internal processing logic in the AudioAnalysisService prioritizes resilience by catching processing exceptions and ensuring file cleanup. Future improvements aim to increase the granularity of error reporting to better distinguish between recoverable data issues and critical system failures.