refactor: Remove duplicate router-level exception helpers

All routers now let domain exceptions propagate to the global handlers in main.py
instead of catching and converting them to HTTPException. This eliminates:

- Duplicate exception-to-HTTP-status mappings across 8 routers
- Duplicate helper functions (_bad_gateway, _not_found, _conflict, etc.)
- Inconsistent error response formats

Changes:
- Removed all try/except blocks from routers that catch domain exceptions
- Removed duplicate helper functions from all routers
- Added missing exception handlers to main.py for:
  * ActionNameError
  * FilterNameError
  * JailNameError
  * JailNotFoundInConfigError
  * FilterInvalidRegexError
- Removed unused imports from affected routers

All domain exceptions now propagate to the single authoritative mapping in
main.py, ensuring consistent error codes, messages, and logging across the API.

Affected routers:
- action_config.py: Removed _action_not_found, _bad_request, _not_found helpers
- bans.py: Removed try/except in ban/unban endpoints
- config_misc.py: Removed try/except blocks
- file_config.py: Removed 6 try/except blocks and _service_unavailable helper
- filter_config.py: Removed try/except blocks
- geo.py: Removed try/except in lookup_ip endpoint
- jail_config.py: Removed try/except blocks
- jails.py: Removed try/except blocks
- server.py: Removed try/except blocks

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-23 16:00:37 +02:00
parent b634ce876a
commit 5480dce221
12 changed files with 229 additions and 977 deletions

View File

@@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Annotated
if TYPE_CHECKING:
from app.services.jail_service import IpLookupResult
from fastapi import APIRouter, HTTPException, Path, status
from fastapi import APIRouter, Path
from app.dependencies import (
AuthDep,
@@ -21,7 +21,6 @@ from app.dependencies import (
Fail2BanSocketDep,
HttpSessionDep,
)
from app.exceptions import Fail2BanConnectionError
from app.models.geo import GeoCacheStatsResponse, GeoReResolveResponse, IpLookupResponse
from app.services import geo_service, jail_service
@@ -58,22 +57,11 @@ async def lookup_ip(
HTTPException: 400 when *ip* is not a valid IP address.
HTTPException: 502 when fail2ban is unreachable.
"""
try:
result: IpLookupResult = await jail_service.lookup_ip(
socket_path,
ip,
http_session=http_session,
)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(exc),
) from exc
except Fail2BanConnectionError as exc:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Cannot reach fail2ban: {exc}",
) from exc
result: IpLookupResult = await jail_service.lookup_ip(
socket_path,
ip,
http_session=http_session,
)
return IpLookupResponse(**result)