safraeli commited on
Commit
fde958e
·
verified ·
1 Parent(s): a1a9123

Add error dict detection, raise HTTPException on data provider errors

Browse files
Files changed (1) hide show
  1. backend/api/routes/sensors.py +16 -3
backend/api/routes/sensors.py CHANGED
@@ -2,14 +2,16 @@
2
 
3
  from __future__ import annotations
4
 
 
5
  from enum import Enum
6
  from typing import Optional
7
 
8
- from fastapi import APIRouter, Depends, Query
9
 
10
  from backend.api.deps import get_datahub
11
  from src.data.data_providers import DataHub
12
 
 
13
  router = APIRouter()
14
 
15
 
@@ -25,12 +27,22 @@ class AreaType(str, Enum):
25
  ambient = "ambient"
26
 
27
 
 
 
 
 
 
 
 
 
 
28
  @router.get("/snapshot")
29
  async def sensors_snapshot(
30
  light: bool = False,
31
  hub: DataHub = Depends(get_datahub),
32
  ):
33
- return hub.vine_sensors.get_snapshot(light=light)
 
34
 
35
 
36
  @router.get("/history")
@@ -40,8 +52,9 @@ async def sensors_history(
40
  hours: int = Query(24, ge=1, le=8760, description="Hours of history (1–8760)"),
41
  hub: DataHub = Depends(get_datahub),
42
  ):
43
- return hub.vine_sensors.get_history(
44
  device_type=type.value,
45
  area=area.value if area else "treatment",
46
  hours_back=hours,
47
  )
 
 
2
 
3
  from __future__ import annotations
4
 
5
+ import logging
6
  from enum import Enum
7
  from typing import Optional
8
 
9
+ from fastapi import APIRouter, Depends, HTTPException, Query
10
 
11
  from backend.api.deps import get_datahub
12
  from src.data.data_providers import DataHub
13
 
14
+ log = logging.getLogger(__name__)
15
  router = APIRouter()
16
 
17
 
 
27
  ambient = "ambient"
28
 
29
 
30
+ def _check_error(result: dict, context: str = "") -> dict:
31
+ """If a data provider returned an error dict, raise HTTPException."""
32
+ if isinstance(result, dict) and "error" in result:
33
+ msg = result["error"]
34
+ log.warning("Data provider error%s: %s", f" ({context})" if context else "", msg)
35
+ raise HTTPException(status_code=502, detail=msg)
36
+ return result
37
+
38
+
39
  @router.get("/snapshot")
40
  async def sensors_snapshot(
41
  light: bool = False,
42
  hub: DataHub = Depends(get_datahub),
43
  ):
44
+ result = hub.vine_sensors.get_snapshot(light=light)
45
+ return _check_error(result, "snapshot")
46
 
47
 
48
  @router.get("/history")
 
52
  hours: int = Query(24, ge=1, le=8760, description="Hours of history (1–8760)"),
53
  hub: DataHub = Depends(get_datahub),
54
  ):
55
+ result = hub.vine_sensors.get_history(
56
  device_type=type.value,
57
  area=area.value if area else "treatment",
58
  hours_back=hours,
59
  )
60
+ return _check_error(result, "sensor history")