Implement new global exceptions and replace old exception handlers in each logic file

This commit is contained in:
Kazgatari
2026-06-29 13:58:29 +02:00
parent 65bb29ecd8
commit 4d85562088
12 changed files with 107 additions and 180 deletions
@@ -1,12 +1,8 @@
import logging
from typing import Any
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE
from . import model
from inse.exceptions import MissingApiKeyError, ElasticsearchException
from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException
from .search_client import CompanyConnectionsSearchClient
logger = logging.getLogger(__name__)
@@ -24,22 +20,10 @@ async def get_company_connections_by_author_id(
) -> model.CompanyConnectionsResponse:
search_client = client or CompanyConnectionsSearchClient()
try:
author_hit = await search_client.get_openalex_author(author_id)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Elasticsearch is not configured.",
) from exc
except ElasticsearchException as exc:
logger.exception("OpenAlex author lookup failed for %s.", author_id)
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex author lookup failed.",
) from exc
author_hit = await search_client.get_openalex_author(author_id)
if author_hit is None:
raise HTTPException(status_code=404, detail=f"Author {author_id} not found.")
raise NotFoundException(f"Author {author_id} not found.")
source = author_hit.get("_source", {})
display_name = _clean(source.get("display_name"))
@@ -60,21 +44,9 @@ async def get_company_connections_by_author_id(
connections=[],
)
try:
hr_response = await search_client.search_handelsregister_by_officer_name(
display_name
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Elasticsearch is not configured.",
) from exc
except ElasticsearchException as exc:
logger.exception("Handelsregister lookup failed for %s.", display_name)
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Handelsregister lookup failed.",
) from exc
hr_response = await search_client.search_handelsregister_by_officer_name(
display_name
)
company_count, company_count_relation = _parse_total(hr_response)
connections = _parse_company_connections(
+13
View File
@@ -21,3 +21,16 @@ class ElasticsearchConnectionException(ElasticsearchException):
class MissingApiKeyError(Exception):
"""Raised when a required API key is missing."""
pass
class UpstreamAPIException(Exception):
"""Raised when an upstream third-party service (e.g. REST API) fails."""
def __init__(self, message: str, status_code: int = 502):
self.message = message
self.status_code = status_code
super().__init__(message)
class BadRequestException(Exception):
"""Raised when request parameters are invalid or validation fails."""
pass
+11 -30
View File
@@ -6,16 +6,10 @@
import logging
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from ..persons import logic as person_logic
from . import model
from .elastic_search_client import FundedPublicationsSearchClient
from inse.exceptions import MissingApiKeyError
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
logger = logging.getLogger(__name__)
@@ -92,9 +86,9 @@ async def get_funders_by_author_id(
)
except ValidationError as exc:
logger.exception("Funders response could not be validated for author %s.", author_id)
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Funders response could not be parsed.",
raise UpstreamAPIException(
message="Funders response could not be parsed.",
status_code=502,
) from exc
@@ -144,26 +138,13 @@ async def _search_funded_publications(
*,
funded_only: bool = False,
) -> dict:
try:
payload = search_client.publications_by_author_query(
author_id,
page,
page_size,
funded_only=funded_only,
)
return await search_client.search(payload)
except MissingApiKeyError as exc:
logger.error("OpenAlex works Elasticsearch API key is not configured.")
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="OpenAlex works search is not configured.",
) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex works search request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
payload = search_client.publications_by_author_query(
author_id,
page,
page_size,
funded_only=funded_only,
)
return await search_client.search(payload)
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
+9 -14
View File
@@ -9,10 +9,8 @@ from copy import deepcopy
from typing import Any, Optional
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_502_BAD_GATEWAY
from inse.exceptions import UpstreamAPIException, BadRequestException
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
@@ -58,10 +56,7 @@ async def list_institutions(
client: OpenAlexInstitutionsClient | None = None,
) -> InstitutionsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail="sample cannot be combined with sort or page.",
)
raise BadRequestException("sample cannot be combined with sort or page.")
openalex_client = client or OpenAlexInstitutionsClient()
@@ -86,12 +81,12 @@ async def list_institutions(
except ValueError:
if exc.response.text:
detail = exc.response.text
raise HTTPException(status_code=status_code, detail=detail) from exc
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex institutions request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex institutions request failed.",
raise UpstreamAPIException(
message="OpenAlex institutions request failed.",
status_code=502,
) from exc
try:
@@ -102,9 +97,9 @@ async def list_institutions(
)
except ValidationError as exc:
logger.exception("OpenAlex institutions response could not be parsed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex institutions response could not be parsed.",
raise UpstreamAPIException(
message="OpenAlex institutions response could not be parsed.",
status_code=502,
) from exc
@@ -1,6 +1,6 @@
import httpx
import pytest
from fastapi import HTTPException
from inse.exceptions import BadRequestException
from inse.institutions import logic
from inse.institutions.search_client import OpenAlexInstitutionsClient
@@ -96,11 +96,9 @@ async def test_list_institutions_maps_openalex_response_to_model():
@pytest.mark.anyio
async def test_list_institutions_rejects_sample_with_sort():
with pytest.raises(HTTPException) as exc_info:
with pytest.raises(BadRequestException) as exc_info:
await logic.list_institutions(sample=10, sort="works_count:desc")
assert exc_info.value.status_code == 400
@pytest.mark.anyio
async def test_list_institutions_accepts_practical_openalex_type_variants():
+27 -1
View File
@@ -14,7 +14,13 @@ from fastapi.responses import JSONResponse, RedirectResponse
from inse.collaboration_network.router import router as collaboration_network_router
from inse.company_connections.service import router as company_connections_router
from inse.exceptions import NotFoundException, ElasticsearchException
from inse.exceptions import (
NotFoundException,
ElasticsearchException,
MissingApiKeyError,
UpstreamAPIException,
BadRequestException,
)
from inse.funders.service import router as funders_service_router
from inse.projects.router import router as projects_router
from inse.university_ranking.router import router as university_ranking_router
@@ -78,6 +84,8 @@ app.add_middleware(
)
# exception handlers
@app.exception_handler(NotFoundException)
async def handle_not_found(request: Request, exc: NotFoundException):
return JSONResponse(status_code=404, content={"message": str(exc)})
@@ -89,6 +97,24 @@ async def handle_elasticsearch_error(request: Request, exc: ElasticsearchExcepti
return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
@app.exception_handler(MissingApiKeyError)
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
logger.error("Configuration error: %s", str(exc))
return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
@app.exception_handler(UpstreamAPIException)
async def handle_upstream_api_error(request: Request, exc: UpstreamAPIException):
logger.error("Upstream API error: %s", str(exc))
return JSONResponse(status_code=exc.status_code, content={"message": exc.message})
@app.exception_handler(BadRequestException)
async def handle_bad_request(request: Request, exc: BadRequestException):
logger.error("Bad Request: %s", str(exc))
return JSONResponse(status_code=400, content={"message": str(exc)})
@app.exception_handler(404)
async def redirect(_, __):
return RedirectResponse(url="/inse-webapp/")
+5 -12
View File
@@ -8,8 +8,7 @@ import json
import logging
import re
from fastapi import HTTPException
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
from inse.exceptions import ElasticsearchException
from ..integrations import elasticsearch, llm
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
@@ -234,12 +233,9 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
source=["date", "maintitle", "author", "url", "full_content"],
cluster="inse",
)
except Exception as exc:
except ElasticsearchException as exc:
logger.exception("Abruf des News-Artikels fehlgeschlagen.")
raise HTTPException(
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
detail="Etwas ist schiefgelaufen.",
) from exc
raise
source = response.get("_source", {})
@@ -435,12 +431,9 @@ async def _run_search(query: dict, source: list, size: int, offset: int, sort, h
highlight=highlight,
cluster="inse",
)
except Exception as exc:
except ElasticsearchException as exc:
logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.")
raise HTTPException(
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
detail="Etwas ist schiefgelaufen.",
) from exc
raise
async def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
+5 -22
View File
@@ -7,15 +7,11 @@ import logging
import asyncio
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from starlette.status import HTTP_404_NOT_FOUND
from ..persons import logic as person_logic
from ..models.openalex.author import Author
from . import model
from inse.exceptions import MissingApiKeyError
from inse.exceptions import MissingApiKeyError, ElasticsearchException
from .elastic_search_client import PatentSearchClient
from .elastic_search_all_patents_client import AllPatentsSearchClient
from .ipc_search_client import IpcSearchClient
@@ -76,16 +72,9 @@ async def get_patents_by_author_id(
patents=[],
)
try:
epo_data, uspto_data = await _search_both_indices(
search_client, last_name, first_name
)
except MissingApiKeyError as exc:
raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.") from exc
except httpx.HTTPError as exc:
raise HTTPException(status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.") from exc
epo_data, uspto_data = await _search_both_indices(
search_client, last_name, first_name
)
all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
@@ -203,7 +192,7 @@ async def _enrich_patents_classifications(
except MissingApiKeyError:
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
return
except httpx.HTTPError as exc:
except ElasticsearchException as exc:
logger.warning("Classification enrichment failed: %s", exc)
return
except Exception as exc:
@@ -314,12 +303,6 @@ async def get_all_patents(
uspto_data.get("hits", {}).get("total", {}).get("value", 0)
)
except MissingApiKeyError as exc:
raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.") from exc
except httpx.HTTPError as exc:
raise HTTPException(status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.") from exc
await _enrich_patents_classifications(patents, ipc_search_client)
+11 -25
View File
@@ -11,13 +11,12 @@ from datetime import datetime
from typing import Optional, Callable, Any, List
import hashlib
import httpx
from fastapi import HTTPException
from inse.exceptions import (
NotFoundException,
ElasticsearchException,
ElasticsearchNotFoundException,
ElasticsearchConnectionException,
BadRequestException,
)
from inse.model import ESIndex
@@ -474,7 +473,7 @@ async def search_persons_by_name(
include: Optional[str] = None,
) -> AuthorsListResponse:
if not author_name:
raise HTTPException(status_code=400, detail="name must be provided")
raise BadRequestException("name must be provided")
search_query = {
"bool": {
"should": [
@@ -506,10 +505,8 @@ async def search_persons_by_name(
track_total_hits=True,
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
except ElasticsearchException as e:
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
hits = response.get("hits", {}).get("hits", [])
@@ -524,7 +521,7 @@ async def search_persons_autocomplete(
author_name: str, limit: Optional[int] = 5, include: Optional[str] = None
) -> AuthorsListResponse:
if not author_name:
raise HTTPException(status_code=400, detail="name must be provided")
raise BadRequestException("name must be provided")
search_query = {
"function_score": {
"query": {
@@ -558,10 +555,8 @@ async def search_persons_autocomplete(
}
try:
response = await elasticsearch.search(index="openalex-authors", body=body)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
except ElasticsearchException as e:
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
hits = response.get("hits", {}).get("hits", [])
@@ -597,7 +592,7 @@ async def search_persons_by_institution(
) -> AuthorsListResponse:
if not institution_name:
raise HTTPException(status_code=400, detail="institution_name must be provided")
raise BadRequestException("institution_name must be provided")
search_query = {
"nested": {
@@ -626,10 +621,8 @@ async def search_persons_by_institution(
track_total_hits=True,
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
except ElasticsearchException as e:
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
hits = response.get("hits", {}).get("hits", [])
persons = [util.get_persons_data(hit) for hit in hits]
@@ -720,14 +713,7 @@ async def advanced_search_persons(
)
except ElasticsearchException as e:
logger.error(f"Elasticsearch search failed: {str(e)}")
raise HTTPException(
status_code=502, detail="Search service temporarily unavailable"
)
except Exception as e:
logger.error(f"Elasticsearch search failed: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
raise
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
hits = response_dict.get("hits", {}).get("hits", [])
+14 -31
View File
@@ -8,10 +8,8 @@ from copy import deepcopy
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_502_BAD_GATEWAY
from inse.exceptions import UpstreamAPIException, BadRequestException, ElasticsearchException
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
@@ -38,10 +36,7 @@ async def list_topics(
client: OpenAlexTopicsClient | None = None,
) -> TopicsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail="sample cannot be combined with sort or page.",
)
raise BadRequestException("sample cannot be combined with sort or page.")
openalex_client = client or OpenAlexTopicsClient()
@@ -66,12 +61,12 @@ async def list_topics(
except ValueError:
if exc.response.text:
detail = exc.response.text
raise HTTPException(status_code=status_code, detail=detail) from exc
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex topics request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex topics request failed.",
raise UpstreamAPIException(
message="OpenAlex topics request failed.",
status_code=502,
) from exc
try:
@@ -79,9 +74,9 @@ async def list_topics(
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
except ValidationError as exc:
logger.exception("OpenAlex topics response could not be parsed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex topics response could not be parsed.",
raise UpstreamAPIException(
message="OpenAlex topics response could not be parsed.",
status_code=502,
) from exc
@@ -282,10 +277,7 @@ async def vector_search_topics(
except Exception as exc:
logger.exception("Failed to load elasticsearch integration.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Failed to load elasticsearch integration: {exc}"
)
raise ElasticsearchException(f"Failed to load elasticsearch integration: {exc}") from exc
# 1. Vectorize query
try:
@@ -293,10 +285,7 @@ async def vector_search_topics(
query_vector = model.encode(query).tolist()
except Exception as exc:
logger.exception("Failed to encode query text.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Failed to encode query text: {exc}"
)
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
# 2. Query Elasticsearch using standard Bool Should hybrid search
should_clauses = []
@@ -363,11 +352,8 @@ async def vector_search_topics(
cluster="nes"
)
except Exception as exc:
logger.exception("Elasticsearch vector search failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Elasticsearch vector search failed: {exc}"
)
logger.exception("Elasticsearch vector search failed with unexpected error.")
raise ElasticsearchException(f"Unexpected vector search failure: {exc}") from exc
# 3. Format result
hits = raw_results.get("hits", {}).get("hits", [])
@@ -389,8 +375,5 @@ async def vector_search_topics(
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
except ValidationError as exc:
logger.exception("Vector search response could not be parsed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Vector search response could not be parsed.",
) from exc
raise ElasticsearchException(f"Vector search response could not be parsed: {exc}") from exc
+2 -4
View File
@@ -1,6 +1,6 @@
import httpx
import pytest
from fastapi import HTTPException
from inse.exceptions import BadRequestException
from inse.topics import logic
from inse.topics.search_client import OpenAlexTopicsClient
@@ -76,11 +76,9 @@ async def test_list_topics_maps_openalex_response_to_model():
@pytest.mark.anyio
async def test_list_topics_rejects_sample_with_sort():
with pytest.raises(HTTPException) as exc_info:
with pytest.raises(BadRequestException) as exc_info:
await logic.list_topics(sample=10, sort="works_count:desc")
assert exc_info.value.status_code == 400
@pytest.mark.anyio
async def test_list_topics_accepts_practical_openalex_type_variants():
+2 -3
View File
@@ -8,15 +8,14 @@ from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
from fastapi import HTTPException
from starlette.status import HTTP_404_NOT_FOUND
from inse.exceptions import NotFoundException
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
raise HTTPException(HTTP_404_NOT_FOUND)
raise NotFoundException("Not found.")
else:
return value