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.

refactor: add error handling decorator to news routes (#1996)

LearningCircuit44f930bb124d
diff --git a/src/local_deep_research/web/routes/news_routes.py b/src/local_deep_research/web/routes/news_routes.py
index 663ad149e9..a6e7092411 100644
--- a/src/local_deep_research/web/routes/news_routes.py
+++ b/src/local_deep_research/web/routes/news_routes.py
@@ -2,6 +2,8 @@
Flask routes for news API endpoints.
"""
+from functools import wraps
+
from flask import Blueprint, jsonify, request, session
from loguru import logger
@@ -13,6 +15,22 @@ from ..auth.decorators import login_required
bp = Blueprint("news_api", __name__, url_prefix="/api/news")
+def handle_api_errors(f):
+ """Decorator to handle API errors consistently across news endpoints."""
+
+ @wraps(f)
+ def wrapper(*args, **kwargs):
+ try:
+ return f(*args, **kwargs)
+ except NewsAPIException:
+ raise
+ except Exception:
+ logger.exception("Unexpected error in %s", f.__name__)
+ return jsonify({"error": "Internal server error"}), 500
+
+ return wrapper
+
+
@bp.errorhandler(NewsAPIException)
def handle_news_api_exception(error: NewsAPIException):
"""Handle NewsAPIException and convert to JSON response."""
@@ -22,234 +40,165 @@ def handle_news_api_exception(error: NewsAPIException):
@bp.route("/feed", methods=["GET"])
@login_required
+@handle_api_errors
def get_news_feed():
"""Get personalized news feed."""
- try:
- user_id = session.get("username")
- 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
+ user_id = session.get("username")
+ 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)
@bp.route("/debug/research", methods=["GET"])
@login_required
+@handle_api_errors
def debug_research_items():
"""Debug endpoint to check research items in database."""
- try:
- user_id = session.get("username")
- 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
+ user_id = session.get("username")
+ result = news_api.debug_research_items(user_id)
+ return jsonify(result)
@bp.route("/subscriptions", methods=["GET"])
@login_required
+@handle_api_errors
def get_subscriptions():
"""Get all subscriptions for the current user."""
- try:
- user_id = session.get("username")
- 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
+ user_id = session.get("username")
+ result = news_api.get_subscriptions(user_id)
+ return jsonify(result)
@bp.route("/subscriptions", methods=["POST"])
@login_required
+@handle_api_errors
def create_subscription():
"""Create a new subscription."""
- try:
- user_id = session.get("username")
- 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
+ user_id = session.get("username")
+ 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
@bp.route("/subscriptions/<subscription_id>", methods=["GET"])
@login_required
+@handle_api_errors
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
+ result = news_api.get_subscription(subscription_id)
+ return jsonify(result)
@bp.route("/subscriptions/<subscription_id>", methods=["PUT", "PATCH"])
@login_required
+@handle_api_errors
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
+ data = request.get_json()
+ result = news_api.update_subscription(subscription_id, data)
+ return jsonify(result)
@bp.route("/subscriptions/<subscription_id>", methods=["DELETE"])
@login_required
+@handle_api_errors
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
+ result = news_api.delete_subscription(subscription_id)
+ return jsonify(result)
@bp.route("/subscriptions/<subscription_id>/history", methods=["GET"])
@login_required
+@handle_api_errors
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
+ limit = request.args.get("limit", 20, type=int)
+ result = news_api.get_subscription_history(subscription_id, limit)
+ return jsonify(result)
@bp.route("/feedback", methods=["POST"])
@login_required
+@handle_api_errors
def submit_feedback():
"""Submit feedback (vote) for a news card."""
- try:
- user_id = session.get("username")
- data = request.get_json()
+ user_id = session.get("username")
+ data = request.get_json()
- card_id = data.get("card_id")
- vote = data.get("vote")
+ 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
+ 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
+ result = news_api.submit_feedback(card_id, user_id, vote)
+ return jsonify(result)
@bp.route("/research", methods=["POST"])
@login_required
+@handle_api_errors
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")
+ 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
+ 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
+ result = news_api.research_news_item(card_id, depth)
+ return jsonify(result)
@bp.route("/preferences", methods=["POST"])
@login_required
+@handle_api_errors
def save_preferences():
"""Save user preferences for news."""
- try:
- user_id = session.get("username")
- preferences = request.get_json()
+ user_id = session.get("username")
+ 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
+ result = news_api.save_news_preferences(user_id, preferences)
+ return jsonify(result)
@bp.route("/categories", methods=["GET"])
@login_required
+@handle_api_errors
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
+ result = news_api.get_news_categories()
+ return jsonify(result)
diff --git a/tests/web/routes/test_news_routes.py b/tests/web/routes/test_news_routes.py
index e7ae0bcbb5..3a7459dd0b 100644
--- a/tests/web/routes/test_news_routes.py
+++ b/tests/web/routes/test_news_routes.py
@@ -11,6 +11,8 @@ Tests cover:
from unittest.mock import patch
+import pytest
+
class TestGetNewsFeed:
"""Tests for get_news_feed endpoint."""
@@ -403,3 +405,79 @@ class TestNewsAPIExceptionHandler:
assert response.status_code == 400
data = response.get_json()
assert data["error_code"] == "TEST_ERROR"
+
+
+class TestHandleApiErrorsDecorator:
+ """Tests for handle_api_errors decorator (PR #1996).
+
+ The decorator catches generic exceptions and returns 500,
+ but re-raises NewsAPIException for the error handler.
+ """
+
+ def test_decorator_returns_500_on_generic_exception(self):
+ """Generic exceptions return 500 JSON response."""
+ from flask import Flask
+
+ from local_deep_research.web.routes.news_routes import (
+ handle_api_errors,
+ )
+
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+
+ with app.app_context():
+
+ @handle_api_errors
+ def failing_view():
+ raise RuntimeError("Unexpected error")
+
+ response, status = failing_view()
+ assert status == 500
+ data = response.get_json()
+ assert "error" in data
+
+ def test_decorator_reraises_news_api_exception(self):
+ """NewsAPIException is re-raised, not caught."""
+ from local_deep_research.news.exceptions import NewsAPIException
+ from local_deep_research.web.routes.news_routes import (
+ handle_api_errors,
+ )
+
+ @handle_api_errors
+ def news_error_view():
+ raise NewsAPIException("Test news error")
+
+ with pytest.raises(NewsAPIException):
+ news_error_view()
+
+ def test_decorator_passes_through_on_success(self):
+ """Successful function result is passed through."""
+ from flask import Flask, jsonify
+
+ from local_deep_research.web.routes.news_routes import (
+ handle_api_errors,
+ )
+
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+
+ with app.app_context():
+
+ @handle_api_errors
+ def ok_view():
+ return jsonify({"status": "ok"}), 200
+
+ response, status = ok_view()
+ assert status == 200
+
+ def test_decorator_preserves_function_name(self):
+ """Decorator preserves wrapped function name."""
+ from local_deep_research.web.routes.news_routes import (
+ handle_api_errors,
+ )
+
+ @handle_api_errors
+ def my_news_endpoint():
+ pass
+
+ assert my_news_endpoint.__name__ == "my_news_endpoint"