Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix: Replace error dicts with exceptions in news API (issue #612) (#630)

LearningCircuit898eee20e5c9
diff --git a/docs/news/EXCEPTION_HANDLING.md b/docs/news/EXCEPTION_HANDLING.md
new file mode 100644
index 0000000000..8d26eb8350
--- /dev/null
+++ b/docs/news/EXCEPTION_HANDLING.md
@@ -0,0 +1,221 @@
+# News API Exception Handling
+
+## Overview
+
+The news API module now uses a structured exception handling approach instead of returning error dictionaries. This provides better error handling, cleaner code, and consistent API responses.
+
+## Exception Hierarchy
+
+All news API exceptions inherit from `NewsAPIException`, which provides:
+- Human-readable error messages
+- HTTP status codes
+- Machine-readable error codes
+- Optional additional details
+
+```python
+from local_deep_research.news.exceptions import NewsAPIException
+
+class NewsAPIException(Exception):
+ def __init__(self, message: str, status_code: int = 500,
+ error_code: Optional[str] = None,
+ details: Optional[Dict[str, Any]] = None)
+```
+
+## Available Exceptions
+
+### InvalidLimitException
+- **Status Code**: 400
+- **Error Code**: `INVALID_LIMIT`
+- **Usage**: When an invalid limit parameter is provided
+- **Example**:
+```python
+if limit < 1:
+ raise InvalidLimitException(limit)
+```
+
+### SubscriptionNotFoundException
+- **Status Code**: 404
+- **Error Code**: `SUBSCRIPTION_NOT_FOUND`
+- **Usage**: When a requested subscription doesn't exist
+- **Example**:
+```python
+if not subscription:
+ raise SubscriptionNotFoundException(subscription_id)
+```
+
+### SubscriptionCreationException
+- **Status Code**: 500
+- **Error Code**: `SUBSCRIPTION_CREATE_FAILED`
+- **Usage**: When subscription creation fails
+- **Example**:
+```python
+except Exception as e:
+ raise SubscriptionCreationException(str(e), {"query": query})
+```
+
+### SubscriptionUpdateException
+- **Status Code**: 500
+- **Error Code**: `SUBSCRIPTION_UPDATE_FAILED`
+- **Usage**: When subscription update fails
+
+### SubscriptionDeletionException
+- **Status Code**: 500
+- **Error Code**: `SUBSCRIPTION_DELETE_FAILED`
+- **Usage**: When subscription deletion fails
+
+### DatabaseAccessException
+- **Status Code**: 500
+- **Error Code**: `DATABASE_ERROR`
+- **Usage**: When database operations fail
+- **Example**:
+```python
+except Exception as e:
+ raise DatabaseAccessException("operation_name", str(e))
+```
+
+### NewsFeedGenerationException
+- **Status Code**: 500
+- **Error Code**: `FEED_GENERATION_FAILED`
+- **Usage**: When news feed generation fails
+
+### ResearchProcessingException
+- **Status Code**: 500
+- **Error Code**: `RESEARCH_PROCESSING_FAILED`
+- **Usage**: When processing research items fails
+
+### NotImplementedException
+- **Status Code**: 501
+- **Error Code**: `NOT_IMPLEMENTED`
+- **Usage**: For features not yet implemented
+- **Example**:
+```python
+raise NotImplementedException("feature_name")
+```
+
+### InvalidParameterException
+- **Status Code**: 400
+- **Error Code**: `INVALID_PARAMETER`
+- **Usage**: When invalid parameters are provided
+
+### SchedulerNotificationException
+- **Status Code**: 500
+- **Error Code**: `SCHEDULER_NOTIFICATION_FAILED`
+- **Usage**: When scheduler notification fails (non-critical)
+
+## Flask Integration
+
+### Error Handlers
+
+The Flask application automatically handles `NewsAPIException` and its subclasses:
+
+```python
[email protected](NewsAPIException)
+def handle_news_api_exception(error):
+ return jsonify(error.to_dict()), error.status_code
+```
+
+### Response Format
+
+All exceptions are converted to consistent JSON responses:
+
+```json
+{
+ "error": "Human-readable error message",
+ "error_code": "MACHINE_READABLE_CODE",
+ "status_code": 400,
+ "details": {
+ "additional": "context",
+ "if": "available"
+ }
+}
+```
+
+## Migration Guide
+
+### Before (Error Dictionaries)
+
+```python
+def get_news_feed(limit):
+ if limit < 1:
+ return {
+ "error": "Limit must be at least 1",
+ "news_items": []
+ }
+
+ try:
+ # ... code ...
+ except Exception as e:
+ logger.exception("Error getting news feed")
+ return {"error": str(e), "news_items": []}
+```
+
+### After (Exceptions)
+
+```python
+def get_news_feed(limit):
+ if limit < 1:
+ raise InvalidLimitException(limit)
+
+ try:
+ # ... code ...
+ except NewsAPIException:
+ raise # Re-raise our custom exceptions
+ except Exception as e:
+ logger.exception("Error getting news feed")
+ raise NewsFeedGenerationException(str(e))
+```
+
+## Benefits
+
+1. **Cleaner Code**: Functions focus on their primary logic without error response formatting
+2. **Consistent Error Handling**: All errors follow the same format
+3. **Better Testing**: Easier to test exception cases with pytest.raises
+4. **Type Safety**: IDEs can better understand return types
+5. **Centralized Logging**: Error logging can be handled in one place
+6. **HTTP Status Codes**: Proper HTTP status codes are automatically set
+
+## Testing
+
+Test exception handling using pytest:
+
+```python
+import pytest
+from local_deep_research.news.exceptions import InvalidLimitException
+
+def test_invalid_limit():
+ with pytest.raises(InvalidLimitException) as exc_info:
+ news_api.get_news_feed(limit=-1)
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.details["provided_limit"] == -1
+```
+
+## Best Practices
+
+1. **Always catch and re-raise NewsAPIException subclasses**:
+```python
+except NewsAPIException:
+ raise # Let Flask handle it
+except Exception as e:
+ # Convert to appropriate NewsAPIException
+ raise DatabaseAccessException("operation", str(e))
+```
+
+2. **Include relevant details**:
+```python
+raise SubscriptionCreationException(
+ "Database constraint violated",
+ details={"query": query, "type": subscription_type}
+)
+```
+
+3. **Use appropriate exception types**: Choose the most specific exception that matches the error condition
+
+4. **Log before raising**: For unexpected errors, log the full exception before converting to NewsAPIException
+
+## Future Improvements
+
+- Add retry logic for transient errors
+- Implement exception metrics/monitoring
+- Add internationalization support for error messages
+- Create exception middleware for advanced error handling
diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.py
index b9af6674a3..d61cd21551 100644
--- a/src/local_deep_research/news/api.py
+++ b/src/local_deep_research/news/api.py
@@ -10,6 +10,17 @@ import re
import json
from .recommender.topic_based import TopicBasedRecommender
+from .exceptions import (
+ InvalidLimitException,
+ SubscriptionNotFoundException,
+ SubscriptionCreationException,
+ SubscriptionUpdateException,
+ SubscriptionDeletionException,
+ DatabaseAccessException,
+ NewsFeedGenerationException,
+ NotImplementedException,
+ NewsAPIException,
+)
# Removed welcome feed import - no placeholders
# get_db_setting not available in merged codebase
@@ -97,10 +108,7 @@ def get_news_feed(
try:
# Validate limit - allow any positive number
if limit < 1:
- return {
- "error": "Limit must be at least 1",
- "news_items": [],
- }
+ raise InvalidLimitException(limit)
logger.info(
f"get_news_feed called with user_id={user_id}, limit={limit}"
@@ -438,7 +446,9 @@ def get_news_feed(
except Exception as db_error:
logger.exception(f"Database error in research history: {db_error}")
- # Continue with what we have from news_items table
+ raise DatabaseAccessException(
+ "research_history_query", str(db_error)
+ )
# If no news items found, return empty list
if not news_items:
@@ -463,12 +473,12 @@ def get_news_feed(
"source": source,
}
- except Exception:
+ except NewsAPIException:
+ # Re-raise our custom exceptions
+ raise
+ except Exception as e:
logger.exception("Error getting news feed")
- return {
- "error": "An error occurred while getting news feed",
- "news_items": [],
- }
+ raise NewsFeedGenerationException(str(e), user_id=user_id)
def debug_research_items(user_id: str):
@@ -524,9 +534,9 @@ def debug_research_items(user_id: str):
"by_status": status_counts,
"recent_items": recent,
}
- except Exception:
+ except Exception as e:
logger.exception("Error in debug_research_items")
- return {"error": "An error occurred while debugging research items"}
+ raise DatabaseAccessException("debug_research_items", str(e))
def get_subscription_history(
@@ -556,7 +566,7 @@ def get_subscription_history(
)
if not subscription:
- return {"error": "Subscription not found", "history": []}
+ raise SubscriptionNotFoundException(subscription_id)
# Convert to dict for response
subscription_dict = {
@@ -654,12 +664,12 @@ def get_subscription_history(
"total_runs": len(processed_history),
}
- except Exception:
+ except NewsAPIException:
+ # Re-raise our custom exceptions
+ raise
+ except Exception as e:
logger.exception("Error getting subscription history")
- return {
- "error": "An error occurred while getting subscription history",
- "history": [],
- }
+ raise DatabaseAccessException("get_subscription_history", str(e))
def _format_time_ago(timestamp: str) -> str:
@@ -715,7 +725,7 @@ def get_subscription(subscription_id: str) -> Optional[Dict[str, Any]]:
)
if not subscription:
- return None
+ raise SubscriptionNotFoundException(subscription_id)
# Convert to API format matching the template expectations
return {
@@ -743,9 +753,12 @@ def get_subscription(subscription_id: str) -> Optional[Dict[str, Any]]:
else None,
}
- except Exception:
+ except NewsAPIException:
+ # Re-raise our custom exceptions
+ raise
+ except Exception as e:
logger.exception(f"Error getting subscription {subscription_id}")
- return None
+ raise DatabaseAccessException("get_subscription", str(e))
def get_subscriptions(user_id: str) -> Dict[str, Any]:
@@ -805,12 +818,9 @@ def get_subscriptions(user_id: str) -> Dict[str, Any]:
return {"subscriptions": sub_list, "total": len(sub_list)}
- except Exception:
+ except Exception as e:
logger.exception("Error getting subscriptions")
- return {
- "error": "Failed to retrieve subscriptions",
- "subscriptions": [],
- }
+ raise DatabaseAccessException("get_subscriptions", str(e))
def update_subscription(
@@ -839,7 +849,7 @@ def update_subscription(
.first()
)
if not subscription:
- return {"error": "Subscription not found"}
+ raise SubscriptionNotFoundException(subscription_id)
# Update fields
if "name" in data:
@@ -915,9 +925,12 @@ def update_subscription(
},
}
- except Exception:
+ except NewsAPIException:
+ # Re-raise our custom exceptions
+ raise
+ except Exception as e:
logger.exception("Error updating subscription")
- return {"error": "An error occurred while updating the subscription"}
+ raise SubscriptionUpdateException(subscription_id, str(e))
def create_subscription(
@@ -1011,9 +1024,11 @@ def create_subscription(
"refresh_minutes": refresh_minutes,
}
- except Exception:
+ except Exception as e:
logger.exception("Error creating subscription")
- raise
+ raise SubscriptionCreationException(
+ str(e), {"query": query, "type": subscription_type}
+ )
def delete_subscription(subscription_id: str) -> Dict[str, Any]:
@@ -1045,13 +1060,13 @@ def delete_subscription(subscription_id: str) -> Dict[str, Any]:
return {"status": "success", "deleted": subscription_id}
else:
- return {"error": "Subscription not found", "status": "error"}
- except Exception:
+ raise SubscriptionNotFoundException(subscription_id)
+ except NewsAPIException:
+ # Re-raise our custom exceptions
+ raise
+ except Exception as e:
logger.exception("Error deleting subscription")
- return {
- "error": "An error occurred while deleting the subscription",
- "status": "error",
- }
+ raise SubscriptionDeletionException(subscription_id, str(e))
def submit_feedback(card_id: str, user_id: str, vote: str) -> Dict[str, Any]:
@@ -1070,12 +1085,7 @@ def submit_feedback(card_id: str, user_id: str, vote: str) -> Dict[str, Any]:
logger.warning(
"submit_feedback not yet implemented with per-user databases"
)
- return {
- "status": "success",
- "card_id": card_id,
- "upvotes": 0,
- "downvotes": 0,
- }
+ raise NotImplementedException("submit_feedback")
def research_news_item(card_id: str, depth: str = "quick") -> Dict[str, Any]:
@@ -1093,10 +1103,7 @@ def research_news_item(card_id: str, depth: str = "quick") -> Dict[str, Any]:
logger.warning(
"research_news_item not yet implemented with per-user databases"
)
- return {
- "status": "error",
- "message": "Feature not yet implemented with per-user databases",
- }
+ raise NotImplementedException("research_news_item")
def save_news_preferences(
@@ -1116,11 +1123,7 @@ def save_news_preferences(
logger.warning(
"save_news_preferences not yet implemented with per-user databases"
)
- return {
- "status": "success",
- "message": "Preferences feature not yet implemented",
- "preferences": preferences,
- }
+ raise NotImplementedException("save_news_preferences")
def get_news_categories() -> Dict[str, Any]:
@@ -1134,7 +1137,4 @@ def get_news_categories() -> Dict[str, Any]:
logger.warning(
"get_news_categories not yet implemented with per-user databases"
)
- return {
- "categories": [],
- "total_items": 0,
- }
+ raise NotImplementedException("get_news_categories")
diff --git a/src/local_deep_research/news/exceptions.py b/src/local_deep_research/news/exceptions.py
new file mode 100644
index 0000000000..5da69710ac
--- /dev/null
+++ b/src/local_deep_research/news/exceptions.py
@@ -0,0 +1,191 @@
+"""
+Custom exceptions for the news API module.
+
+These exceptions are used to provide structured error handling
+that can be caught by Flask error handlers and converted to
+appropriate JSON responses.
+"""
+
+from typing import Optional, Dict, Any
+
+
+class NewsAPIException(Exception):
+ """Base exception for all news API related errors."""
+
+ def __init__(
+ self,
+ message: str,
+ status_code: int = 500,
+ error_code: Optional[str] = None,
+ details: Optional[Dict[str, Any]] = None,
+ ):
+ """
+ Initialize the news API exception.
+
+ Args:
+ message: Human-readable error message
+ status_code: HTTP status code for the error
+ error_code: Machine-readable error code for API consumers
+ details: Additional error details/context
+ """
+ super().__init__(message)
+ self.message = message
+ self.status_code = status_code
+ self.error_code = error_code or self.__class__.__name__
+ self.details = details or {}
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert exception to dictionary for JSON response."""
+ result = {
+ "error": self.message,
+ "error_code": self.error_code,
+ "status_code": self.status_code,
+ }
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+class NewsFeatureDisabledException(NewsAPIException):
+ """Raised when the news feature is disabled in settings."""
+
+ def __init__(self, message: str = "News system is disabled"):
+ super().__init__(message, status_code=503, error_code="NEWS_DISABLED")
+
+
+class InvalidLimitException(NewsAPIException):
+ """Raised when an invalid limit parameter is provided."""
+
+ def __init__(self, limit: int):
+ super().__init__(
+ f"Invalid limit: {limit}. Limit must be at least 1",
+ status_code=400,
+ error_code="INVALID_LIMIT",
+ details={"provided_limit": limit, "min_limit": 1},
+ )
+
+
+class SubscriptionNotFoundException(NewsAPIException):
+ """Raised when a requested subscription is not found."""
+
+ def __init__(self, subscription_id: str):
+ super().__init__(
+ f"Subscription not found: {subscription_id}",
+ status_code=404,
+ error_code="SUBSCRIPTION_NOT_FOUND",
+ details={"subscription_id": subscription_id},
+ )
+
+
+class SubscriptionCreationException(NewsAPIException):
+ """Raised when subscription creation fails."""
+
+ def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
+ super().__init__(
+ f"Failed to create subscription: {message}",
+ status_code=500,
+ error_code="SUBSCRIPTION_CREATE_FAILED",
+ details=details,
+ )
+
+
+class SubscriptionUpdateException(NewsAPIException):
+ """Raised when subscription update fails."""
+
+ def __init__(self, subscription_id: str, message: str):
+ super().__init__(
+ f"Failed to update subscription {subscription_id}: {message}",
+ status_code=500,
+ error_code="SUBSCRIPTION_UPDATE_FAILED",
+ details={"subscription_id": subscription_id},
+ )
+
+
+class SubscriptionDeletionException(NewsAPIException):
+ """Raised when subscription deletion fails."""
+
+ def __init__(self, subscription_id: str, message: str):
+ super().__init__(
+ f"Failed to delete subscription {subscription_id}: {message}",
+ status_code=500,
+ error_code="SUBSCRIPTION_DELETE_FAILED",
+ details={"subscription_id": subscription_id},
+ )
+
+
+class DatabaseAccessException(NewsAPIException):
+ """Raised when database access fails."""
+
+ def __init__(self, operation: str, message: str):
+ super().__init__(
+ f"Database error during {operation}: {message}",
+ status_code=500,
+ error_code="DATABASE_ERROR",
+ details={"operation": operation},
+ )
+
+
+class NewsFeedGenerationException(NewsAPIException):
+ """Raised when news feed generation fails."""
+
+ def __init__(self, message: str, user_id: Optional[str] = None):
+ details = {}
+ if user_id:
+ details["user_id"] = user_id
+ super().__init__(
+ f"Failed to generate news feed: {message}",
+ status_code=500,
+ error_code="FEED_GENERATION_FAILED",
+ details=details,
+ )
+
+
+class ResearchProcessingException(NewsAPIException):
+ """Raised when processing research items for news fails."""
+
+ def __init__(self, message: str, research_id: Optional[str] = None):
+ details = {}
+ if research_id:
+ details["research_id"] = research_id
+ super().__init__(
+ f"Failed to process research item: {message}",
+ status_code=500,
+ error_code="RESEARCH_PROCESSING_FAILED",
+ details=details,
+ )
+
+
+class NotImplementedException(NewsAPIException):
+ """Raised when a feature is not yet implemented."""
+
+ def __init__(self, feature: str):
+ super().__init__(
+ f"Feature not yet implemented: {feature}",
+ status_code=501,
+ error_code="NOT_IMPLEMENTED",
+ details={"feature": feature},
+ )
+
+
+class InvalidParameterException(NewsAPIException):
+ """Raised when invalid parameters are provided to API functions."""
+
+ def __init__(self, parameter: str, value: Any, message: str):
+ super().__init__(
+ f"Invalid parameter '{parameter}': {message}",
+ status_code=400,
+ error_code="INVALID_PARAMETER",
+ details={"parameter": parameter, "value": value},
+ )
+
+
+class SchedulerNotificationException(NewsAPIException):
+ """Raised when scheduler notification fails (non-critical)."""
+
+ def __init__(self, action: str, message: str):
+ super().__init__(
+ f"Failed to notify scheduler about {action}: {message}",
+ status_code=500,
+ error_code="SCHEDULER_NOTIFICATION_FAILED",
+ details={"action": action},
+ )
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 8ffe19eec2..62f3cde38f 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -336,19 +336,6 @@ def register_blueprints(app):
from .routes.research_routes import research_bp
from .routes.settings_routes import settings_bp
- # Try to import news blueprint
- try:
- from ..news.web import create_news_blueprint
-
- news_available = True
- logger.info("News module imported successfully")
- except ImportError as e:
- news_available = False
- logger.warning(f"News module not available: {e}")
- except Exception:
- news_available = False
- logger.exception("Error importing news module")
-
# Add root route
@app.route("/")
def index():
@@ -400,15 +387,11 @@ def register_blueprints(app):
) # Register API blueprint with prefix
app.register_blueprint(benchmark_bp) # Register benchmark blueprint
- # Register news blueprint if available
- if news_available:
- try:
- news_bp = create_news_blueprint()
- app.register_blueprint(news_bp, url_prefix="/news")
- logger.info("News blueprint registered successfully")
- except Exception:
- logger.exception("Failed to register news blueprint")
- news_available = False
+ # Register news API routes
+ from .routes import news_routes
+
+ app.register_blueprint(news_routes.bp)
+ logger.info("News API routes registered successfully")
# Register API v1 blueprint
app.register_blueprint(api_blueprint) # Already has url_prefix='/api/v1'
@@ -450,6 +433,23 @@ def register_error_handlers(app):
def server_error(error):
return make_response(jsonify({"error": "Server error"}), 500)
+ # Handle News API exceptions globally
+ try:
+ from ..news.exceptions import NewsAPIException
+
+ @app.errorhandler(NewsAPIException)
+ def handle_news_api_exception(error):
+ """Handle NewsAPIException and convert to JSON response."""
+ from loguru import logger
+
+ logger.error(
+ f"News API error: {error.message} (code: {error.error_code})"
+ )
+ return jsonify(error.to_dict()), error.status_code
+ except ImportError:
+ # News module not available
+ pass
+
def create_database(app):
"""
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 7ab56d15ed..71b56a4d17 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -296,11 +296,12 @@ def register():
), 500
-@auth_bp.route("/logout", methods=["POST"])
+@auth_bp.route("/logout", methods=["GET", "POST"])
def logout():
"""
Logout handler.
Clears session and closes database connections.
+ Supports both GET (for direct navigation) and POST (for form submission).
"""
username = session.get("username")
session_id = session.get("session_id")
diff --git a/src/local_deep_research/web/routes/news_routes.py b/src/local_deep_research/web/routes/news_routes.py
new file mode 100644
index 0000000000..6525a0bb93
--- /dev/null
+++ b/src/local_deep_research/web/routes/news_routes.py
@@ -0,0 +1,242 @@
+"""
+Flask routes for news API endpoints.
+"""
+
+from flask import Blueprint, jsonify, request, session
+from loguru import logger
+
+from ...news import api as news_api
+from ...news.exceptions import NewsAPIException
+
+# Create blueprint
+bp = Blueprint("news", __name__, url_prefix="/api/news")
+
+
[email protected](NewsAPIException)
+def handle_news_api_exception(error: NewsAPIException):
+ """Handle NewsAPIException and convert to JSON response."""
+ logger.error(f"News API error: {error.message} (code: {error.error_code})")
+ return jsonify(error.to_dict()), error.status_code
+
+
[email protected]("/feed", methods=["GET"])
+def get_news_feed():
+ """Get personalized news feed."""
+ try:
+ user_id = session.get("username", "anonymous")
+ limit = request.args.get("limit", 20, type=int)
+ use_cache = request.args.get("use_cache", "true").lower() == "true"
+ focus = request.args.get("focus")
+ search_strategy = request.args.get("search_strategy")
+ subscription_id = request.args.get("subscription_id")
+
+ result = news_api.get_news_feed(
+ user_id=user_id,
+ limit=limit,
+ use_cache=use_cache,
+ focus=focus,
+ search_strategy=search_strategy,
+ subscription_id=subscription_id,
+ )
+
+ return jsonify(result)
+ except NewsAPIException:
+ # Let the error handler deal with it
+ raise
+ except Exception:
+ logger.exception("Unexpected error in get_news_feed")
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/debug/research", methods=["GET"])
+def debug_research_items():
+ """Debug endpoint to check research items in database."""
+ try:
+ user_id = session.get("username", "anonymous")
+ result = news_api.debug_research_items(user_id)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception("Unexpected error in debug_research_items")
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/subscriptions", methods=["GET"])
+def get_subscriptions():
+ """Get all subscriptions for the current user."""
+ try:
+ user_id = session.get("username", "anonymous")
+ result = news_api.get_subscriptions(user_id)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception("Unexpected error in get_subscriptions")
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/subscriptions", methods=["POST"])
+def create_subscription():
+ """Create a new subscription."""
+ try:
+ user_id = session.get("username", "anonymous")
+ data = request.get_json()
+
+ result = news_api.create_subscription(
+ user_id=user_id,
+ query=data.get("query"),
+ subscription_type=data.get("type", "search"),
+ refresh_minutes=data.get("refresh_minutes"),
+ source_research_id=data.get("source_research_id"),
+ model_provider=data.get("model_provider"),
+ model=data.get("model"),
+ search_strategy=data.get("search_strategy"),
+ custom_endpoint=data.get("custom_endpoint"),
+ name=data.get("name"),
+ folder_id=data.get("folder_id"),
+ is_active=data.get("is_active", True),
+ search_engine=data.get("search_engine"),
+ search_iterations=data.get("search_iterations"),
+ questions_per_iteration=data.get("questions_per_iteration"),
+ )
+
+ return jsonify(result), 201
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception("Unexpected error in create_subscription")
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/subscriptions/<subscription_id>", methods=["GET"])
+def get_subscription(subscription_id):
+ """Get a single subscription by ID."""
+ try:
+ result = news_api.get_subscription(subscription_id)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception(
+ f"Unexpected error getting subscription {subscription_id}"
+ )
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/subscriptions/<subscription_id>", methods=["PUT", "PATCH"])
+def update_subscription(subscription_id):
+ """Update an existing subscription."""
+ try:
+ data = request.get_json()
+ result = news_api.update_subscription(subscription_id, data)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception(
+ f"Unexpected error updating subscription {subscription_id}"
+ )
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/subscriptions/<subscription_id>", methods=["DELETE"])
+def delete_subscription(subscription_id):
+ """Delete a subscription."""
+ try:
+ result = news_api.delete_subscription(subscription_id)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception(
+ f"Unexpected error deleting subscription {subscription_id}"
+ )
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/subscriptions/<subscription_id>/history", methods=["GET"])
+def get_subscription_history(subscription_id):
+ """Get research history for a specific subscription."""
+ try:
+ limit = request.args.get("limit", 20, type=int)
+ result = news_api.get_subscription_history(subscription_id, limit)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception(
+ f"Unexpected error getting history for {subscription_id}"
+ )
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/feedback", methods=["POST"])
+def submit_feedback():
+ """Submit feedback (vote) for a news card."""
+ try:
+ user_id = session.get("username", "anonymous")
+ data = request.get_json()
+
+ card_id = data.get("card_id")
+ vote = data.get("vote")
+
+ if not card_id or vote not in ["up", "down"]:
+ return jsonify({"error": "Invalid request"}), 400
+
+ result = news_api.submit_feedback(card_id, user_id, vote)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception("Unexpected error in submit_feedback")
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/research", methods=["POST"])
+def research_news_item():
+ """Perform deeper research on a news item."""
+ try:
+ data = request.get_json()
+ card_id = data.get("card_id")
+ depth = data.get("depth", "quick")
+
+ if not card_id:
+ return jsonify({"error": "card_id is required"}), 400
+
+ result = news_api.research_news_item(card_id, depth)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception("Unexpected error in research_news_item")
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/preferences", methods=["POST"])
+def save_preferences():
+ """Save user preferences for news."""
+ try:
+ user_id = session.get("username", "anonymous")
+ preferences = request.get_json()
+
+ result = news_api.save_news_preferences(user_id, preferences)
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception("Unexpected error in save_preferences")
+ return jsonify({"error": "Internal server error"}), 500
+
+
[email protected]("/categories", methods=["GET"])
+def get_categories():
+ """Get available news categories with counts."""
+ try:
+ result = news_api.get_news_categories()
+ return jsonify(result)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception("Unexpected error in get_categories")
+ return jsonify({"error": "Internal server error"}), 500
diff --git a/src/local_deep_research/web/templates/components/mobile_nav.html b/src/local_deep_research/web/templates/components/mobile_nav.html
index d0f0ac1132..c05092c06d 100644
--- a/src/local_deep_research/web/templates/components/mobile_nav.html
+++ b/src/local_deep_research/web/templates/components/mobile_nav.html
@@ -12,6 +12,7 @@
<span>History</span>
</a>
</li>
+ {# News pages not yet implemented
<li {% if active_page == 'news' %}class="active"{% endif %} data-page="news">
<a href="{{ url_for('news.news_page') }}">
<i class="fas fa-newspaper"></i>
@@ -24,6 +25,7 @@
<span>Subscriptions</span>
</a>
</li>
+ #}
<li {% if active_page == 'settings' %}class="active"{% endif %} data-page="settings">
<a href="{{ url_for('settings.settings_page') }}">
<i class="fas fa-cog"></i>
diff --git a/src/local_deep_research/web/templates/components/sidebar.html b/src/local_deep_research/web/templates/components/sidebar.html
index 9d0557cce5..d992c6804f 100644
--- a/src/local_deep_research/web/templates/components/sidebar.html
+++ b/src/local_deep_research/web/templates/components/sidebar.html
@@ -10,12 +10,14 @@
<li {% if active_page == 'history' %}class="active"{% endif %} data-page="history">
<a href="{{ url_for('history.history_page') }}"><i class="fas fa-history"></i> History</a>
</li>
+ {# News pages not yet implemented
<li {% if active_page == 'news' %}class="active"{% endif %} data-page="news">
<a href="{{ url_for('news.news_page') }}"><i class="fas fa-newspaper"></i> News</a>
</li>
<li {% if active_page == 'subscriptions' %}class="active"{% endif %} data-page="subscriptions">
<a href="{{ url_for('news.subscriptions_page') }}"><i class="fas fa-bell"></i> Subscriptions</a>
</li>
+ #}
<li {% if active_page == 'benchmark' %}class="active"{% endif %} data-page="benchmark">
<a href="{{ url_for('benchmark.index') }}"><i class="fas fa-tachometer-alt"></i> Benchmark</a>
</li>
diff --git a/tests/news/test_api_exceptions.py b/tests/news/test_api_exceptions.py
new file mode 100644
index 0000000000..57a91a82fc
--- /dev/null
+++ b/tests/news/test_api_exceptions.py
@@ -0,0 +1,176 @@
+"""
+Test that API functions raise appropriate exceptions instead of returning error dicts.
+"""
+
+import pytest
+from unittest.mock import patch, MagicMock
+
+from local_deep_research.news import api as news_api
+from local_deep_research.news.exceptions import (
+ InvalidLimitException,
+ SubscriptionNotFoundException,
+ SubscriptionCreationException,
+ DatabaseAccessException,
+ NotImplementedException,
+)
+
+
+class TestGetNewsFeedExceptions:
+ """Test exception handling in get_news_feed function."""
+
+ def test_invalid_limit_raises_exception(self):
+ """Test that invalid limit raises InvalidLimitException."""
+ with pytest.raises(InvalidLimitException) as exc_info:
+ news_api.get_news_feed(limit=0)
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.details["provided_limit"] == 0
+
+ def test_negative_limit_raises_exception(self):
+ """Test that negative limit raises InvalidLimitException."""
+ with pytest.raises(InvalidLimitException) as exc_info:
+ news_api.get_news_feed(limit=-10)
+
+ assert exc_info.value.details["provided_limit"] == -10
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_database_error_raises_exception(self, mock_db_session):
+ """Test that database errors raise DatabaseAccessException."""
+ mock_db_session.side_effect = Exception("Connection failed")
+
+ with pytest.raises(DatabaseAccessException) as exc_info:
+ news_api.get_news_feed(user_id="test_user")
+
+ assert exc_info.value.status_code == 500
+ assert "research_history_query" in exc_info.value.details["operation"]
+ assert "Connection failed" in exc_info.value.message
+
+
+class TestSubscriptionExceptions:
+ """Test exception handling in subscription functions."""
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_get_subscription_not_found(self, mock_db_session):
+ """Test that missing subscription raises SubscriptionNotFoundException."""
+ mock_session = MagicMock()
+ mock_db_session.return_value.__enter__.return_value = mock_session
+ mock_session.query().filter_by().first.return_value = None
+
+ with pytest.raises(SubscriptionNotFoundException) as exc_info:
+ news_api.get_subscription("non-existent-id")
+
+ assert exc_info.value.status_code == 404
+ assert exc_info.value.details["subscription_id"] == "non-existent-id"
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_get_subscription_database_error(self, mock_db_session):
+ """Test that database errors in get_subscription raise DatabaseAccessException."""
+ mock_db_session.side_effect = Exception("Database locked")
+
+ with pytest.raises(DatabaseAccessException) as exc_info:
+ news_api.get_subscription("sub-123")
+
+ assert exc_info.value.status_code == 500
+ assert "get_subscription" in exc_info.value.details["operation"]
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_update_subscription_not_found(self, mock_db_session):
+ """Test that updating non-existent subscription raises exception."""
+ mock_session = MagicMock()
+ mock_db_session.return_value.__enter__.return_value = mock_session
+ mock_session.query().filter_by().first.return_value = None
+
+ with pytest.raises(SubscriptionNotFoundException) as exc_info:
+ news_api.update_subscription("non-existent", {"name": "New Name"})
+
+ assert exc_info.value.details["subscription_id"] == "non-existent"
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_delete_subscription_not_found(self, mock_db_session):
+ """Test that deleting non-existent subscription raises exception."""
+ mock_session = MagicMock()
+ mock_db_session.return_value.__enter__.return_value = mock_session
+ mock_session.query().filter_by().first.return_value = None
+
+ with pytest.raises(SubscriptionNotFoundException) as exc_info:
+ news_api.delete_subscription("non-existent")
+
+ assert exc_info.value.details["subscription_id"] == "non-existent"
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_create_subscription_database_error(self, mock_db_session):
+ """Test that database error during creation raises exception."""
+ mock_db_session.side_effect = Exception("Constraint violation")
+
+ with pytest.raises(SubscriptionCreationException) as exc_info:
+ news_api.create_subscription(
+ user_id="test_user",
+ query="test query",
+ subscription_type="search",
+ )
+
+ assert exc_info.value.status_code == 500
+ assert "Constraint violation" in exc_info.value.message
+ assert exc_info.value.details["query"] == "test query"
+
+
+class TestNotImplementedExceptions:
+ """Test that unimplemented features raise NotImplementedException."""
+
+ def test_submit_feedback_not_implemented(self):
+ """Test that submit_feedback raises NotImplementedException."""
+ with pytest.raises(NotImplementedException) as exc_info:
+ news_api.submit_feedback("card-123", "user", "up")
+
+ assert exc_info.value.status_code == 501
+ assert exc_info.value.details["feature"] == "submit_feedback"
+
+ def test_research_news_item_not_implemented(self):
+ """Test that research_news_item raises NotImplementedException."""
+ with pytest.raises(NotImplementedException) as exc_info:
+ news_api.research_news_item("card-123", "detailed")
+
+ assert exc_info.value.details["feature"] == "research_news_item"
+
+ def test_save_preferences_not_implemented(self):
+ """Test that save_news_preferences raises NotImplementedException."""
+ with pytest.raises(NotImplementedException) as exc_info:
+ news_api.save_news_preferences("user", {"theme": "dark"})
+
+ assert exc_info.value.details["feature"] == "save_news_preferences"
+
+ def test_get_categories_not_implemented(self):
+ """Test that get_news_categories raises NotImplementedException."""
+ with pytest.raises(NotImplementedException) as exc_info:
+ news_api.get_news_categories()
+
+ assert exc_info.value.details["feature"] == "get_news_categories"
+
+
+class TestSubscriptionHistoryExceptions:
+ """Test exception handling in subscription history functions."""
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_subscription_history_not_found(self, mock_db_session):
+ """Test that history for non-existent subscription raises exception."""
+ mock_session = MagicMock()
+ mock_db_session.return_value.__enter__.return_value = mock_session
+
+ # First call for subscription lookup returns None
+ mock_session.query().filter_by().first.return_value = None
+
+ with pytest.raises(SubscriptionNotFoundException) as exc_info:
+ news_api.get_subscription_history("non-existent")
+
+ assert exc_info.value.details["subscription_id"] == "non-existent"
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_subscription_history_database_error(self, mock_db_session):
+ """Test that database error in history raises exception."""
+ mock_db_session.side_effect = Exception("Query timeout")
+
+ with pytest.raises(DatabaseAccessException) as exc_info:
+ news_api.get_subscription_history("sub-123")
+
+ assert "get_subscription_history" in exc_info.value.details["operation"]
+ assert "Query timeout" in exc_info.value.message
diff --git a/tests/news/test_exceptions.py b/tests/news/test_exceptions.py
new file mode 100644
index 0000000000..5af5e02da8
--- /dev/null
+++ b/tests/news/test_exceptions.py
@@ -0,0 +1,196 @@
+"""
+Test cases for news API exception handling.
+"""
+
+from local_deep_research.news.exceptions import (
+ NewsAPIException,
+ InvalidLimitException,
+ SubscriptionNotFoundException,
+ SubscriptionCreationException,
+ SubscriptionUpdateException,
+ SubscriptionDeletionException,
+ DatabaseAccessException,
+ NewsFeedGenerationException,
+ ResearchProcessingException,
+ NotImplementedException,
+ InvalidParameterException,
+ SchedulerNotificationException,
+)
+
+
+class TestNewsAPIException:
+ """Test the base NewsAPIException class."""
+
+ def test_basic_exception(self):
+ """Test basic exception creation."""
+ exc = NewsAPIException("Test error", status_code=400)
+
+ assert str(exc) == "Test error"
+ assert exc.message == "Test error"
+ assert exc.status_code == 400
+ assert exc.error_code == "NewsAPIException"
+ assert exc.details == {}
+
+ def test_exception_with_details(self):
+ """Test exception with additional details."""
+ details = {"key": "value", "count": 42}
+ exc = NewsAPIException(
+ "Test error",
+ status_code=500,
+ error_code="CUSTOM_ERROR",
+ details=details,
+ )
+
+ assert exc.error_code == "CUSTOM_ERROR"
+ assert exc.details == details
+
+ def test_to_dict(self):
+ """Test converting exception to dictionary."""
+ exc = NewsAPIException(
+ "Test error",
+ status_code=403,
+ error_code="TEST_ERROR",
+ details={"user": "test"},
+ )
+
+ result = exc.to_dict()
+
+ assert result == {
+ "error": "Test error",
+ "error_code": "TEST_ERROR",
+ "status_code": 403,
+ "details": {"user": "test"},
+ }
+
+ def test_to_dict_without_details(self):
+ """Test converting exception without details."""
+ exc = NewsAPIException("Simple error")
+ result = exc.to_dict()
+
+ assert result == {
+ "error": "Simple error",
+ "error_code": "NewsAPIException",
+ "status_code": 500,
+ }
+
+
+class TestSpecificExceptions:
+ """Test specific exception subclasses."""
+
+ def test_invalid_limit_exception(self):
+ """Test InvalidLimitException."""
+ exc = InvalidLimitException(-5)
+
+ assert exc.status_code == 400
+ assert exc.error_code == "INVALID_LIMIT"
+ assert "-5" in exc.message
+ assert exc.details["provided_limit"] == -5
+ assert exc.details["min_limit"] == 1
+
+ def test_subscription_not_found(self):
+ """Test SubscriptionNotFoundException."""
+ exc = SubscriptionNotFoundException("sub-123")
+
+ assert exc.status_code == 404
+ assert exc.error_code == "SUBSCRIPTION_NOT_FOUND"
+ assert "sub-123" in exc.message
+ assert exc.details["subscription_id"] == "sub-123"
+
+ def test_subscription_creation_exception(self):
+ """Test SubscriptionCreationException."""
+ exc = SubscriptionCreationException(
+ "Database error", {"query": "test query", "type": "search"}
+ )
+
+ assert exc.status_code == 500
+ assert exc.error_code == "SUBSCRIPTION_CREATE_FAILED"
+ assert "Database error" in exc.message
+ assert exc.details["query"] == "test query"
+
+ def test_subscription_update_exception(self):
+ """Test SubscriptionUpdateException."""
+ exc = SubscriptionUpdateException("sub-456", "Invalid data")
+
+ assert exc.status_code == 500
+ assert exc.error_code == "SUBSCRIPTION_UPDATE_FAILED"
+ assert "sub-456" in exc.message
+ assert "Invalid data" in exc.message
+ assert exc.details["subscription_id"] == "sub-456"
+
+ def test_subscription_deletion_exception(self):
+ """Test SubscriptionDeletionException."""
+ exc = SubscriptionDeletionException("sub-789", "Permission denied")
+
+ assert exc.status_code == 500
+ assert exc.error_code == "SUBSCRIPTION_DELETE_FAILED"
+ assert "sub-789" in exc.message
+ assert "Permission denied" in exc.message
+ assert exc.details["subscription_id"] == "sub-789"
+
+ def test_database_access_exception(self):
+ """Test DatabaseAccessException."""
+ exc = DatabaseAccessException("query_operation", "Connection lost")
+
+ assert exc.status_code == 500
+ assert exc.error_code == "DATABASE_ERROR"
+ assert "query_operation" in exc.message
+ assert "Connection lost" in exc.message
+ assert exc.details["operation"] == "query_operation"
+
+ def test_news_feed_generation_exception(self):
+ """Test NewsFeedGenerationException."""
+ exc = NewsFeedGenerationException("Processing error", user_id="user123")
+
+ assert exc.status_code == 500
+ assert exc.error_code == "FEED_GENERATION_FAILED"
+ assert "Processing error" in exc.message
+ assert exc.details["user_id"] == "user123"
+
+ def test_news_feed_generation_without_user(self):
+ """Test NewsFeedGenerationException without user_id."""
+ exc = NewsFeedGenerationException("Processing error")
+
+ assert exc.details == {}
+
+ def test_research_processing_exception(self):
+ """Test ResearchProcessingException."""
+ exc = ResearchProcessingException(
+ "Parse error", research_id="research-001"
+ )
+
+ assert exc.status_code == 500
+ assert exc.error_code == "RESEARCH_PROCESSING_FAILED"
+ assert "Parse error" in exc.message
+ assert exc.details["research_id"] == "research-001"
+
+ def test_not_implemented_exception(self):
+ """Test NotImplementedException."""
+ exc = NotImplementedException("advanced_search")
+
+ assert exc.status_code == 501
+ assert exc.error_code == "NOT_IMPLEMENTED"
+ assert "advanced_search" in exc.message
+ assert exc.details["feature"] == "advanced_search"
+
+ def test_invalid_parameter_exception(self):
+ """Test InvalidParameterException."""
+ exc = InvalidParameterException(
+ "refresh_interval", -100, "Must be positive"
+ )
+
+ assert exc.status_code == 400
+ assert exc.error_code == "INVALID_PARAMETER"
+ assert "refresh_interval" in exc.message
+ assert "Must be positive" in exc.message
+ assert exc.details["parameter"] == "refresh_interval"
+ assert exc.details["value"] == -100
+
+ def test_scheduler_notification_exception(self):
+ """Test SchedulerNotificationException."""
+ exc = SchedulerNotificationException("update", "Service unavailable")
+
+ assert exc.status_code == 500
+ assert exc.error_code == "SCHEDULER_NOTIFICATION_FAILED"
+ assert "update" in exc.message
+ assert "Service unavailable" in exc.message
+ assert exc.details["action"] == "update"