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

@@ -39,20 +39,6 @@ log: structlog.stdlib.BoundLogger = structlog.get_logger()
router: APIRouter = APIRouter(tags=["Config Misc"])
def _bad_gateway(exc: Exception) -> HTTPException:
return HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Cannot reach fail2ban: {exc}",
)
def _bad_request(message: str) -> HTTPException:
return HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=message,
)
@router.get(
"/global",
response_model=GlobalConfigResponse,
@@ -77,10 +63,7 @@ async def get_global_config(
Raises:
HTTPException: 502 when fail2ban is unreachable.
"""
try:
return await config_service.get_global_config(socket_path)
except Fail2BanConnectionError as exc:
raise _bad_gateway(exc) from exc
return await config_service.get_global_config(socket_path)
@router.put(
@@ -105,12 +88,7 @@ async def update_global_config(
HTTPException: 400 when a set command is rejected.
HTTPException: 502 when fail2ban is unreachable.
"""
try:
await config_service.update_global_config(socket_path, body)
except ConfigOperationError as exc:
raise _bad_request(str(exc)) from exc
except Fail2BanConnectionError as exc:
raise _bad_gateway(exc) from exc
await config_service.update_global_config(socket_path, body)
# ---------------------------------------------------------------------------
@@ -139,15 +117,7 @@ async def reload_fail2ban(
HTTPException: 409 when fail2ban reports the reload failed.
HTTPException: 502 when fail2ban is unreachable.
"""
try:
await jail_service.reload_all(socket_path)
except JailOperationError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"fail2ban reload failed: {exc}",
) from exc
except Fail2BanConnectionError as exc:
raise _bad_gateway(exc) from exc
await jail_service.reload_all(socket_path)
# Restart endpoint
@@ -186,18 +156,10 @@ async def restart_fail2ban(
"""
start_cmd_parts: list[str] = start_cmd.split()
try:
restarted = await jail_service.restart_daemon(
socket_path,
start_cmd_parts,
)
except JailOperationError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"fail2ban stop command failed: {exc}",
) from exc
except Fail2BanConnectionError as exc:
raise _bad_gateway(exc) from exc
restarted = await jail_service.restart_daemon(
socket_path,
start_cmd_parts,
)
if not restarted:
raise HTTPException(
@@ -323,11 +285,7 @@ async def update_map_color_thresholds(
HTTPException: 400 if validation fails (thresholds not
properly ordered).
"""
try:
await config_service.update_map_color_thresholds(db, body)
except ValueError as exc:
raise _bad_request(str(exc)) from exc
await config_service.update_map_color_thresholds(db, body)
return await config_service.get_map_color_thresholds(db)
@@ -379,12 +337,7 @@ async def get_fail2ban_log(
the allowed directory.
HTTPException: 502 when fail2ban is unreachable.
"""
try:
return await log_service.read_fail2ban_log(socket_path, lines, filter_)
except ConfigOperationError as exc:
raise _bad_request(str(exc)) from exc
except Fail2BanConnectionError as exc:
raise _bad_gateway(exc) from exc
return await log_service.read_fail2ban_log(socket_path, lines, filter_)
@router.get(
@@ -415,10 +368,7 @@ async def get_service_status(
"""
from app.services import health_service
try:
return await health_service.get_service_status(
socket_path,
probe_fn=health_service.probe,
)
except Fail2BanConnectionError as exc:
raise _bad_gateway(exc) from exc
return await health_service.get_service_status(
socket_path,
probe_fn=health_service.probe,
)