24 lines
823 B
Python
24 lines
823 B
Python
from __future__ import annotations
|
|
|
|
from fastapi import FastAPI, Request, status
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.ha.exceptions import HaAuthError, HaClientError, HaHttpError, HaTimeoutError
|
|
|
|
|
|
def register_exception_handlers(app: FastAPI) -> None:
|
|
@app.exception_handler(HaClientError)
|
|
async def handle_ha_client_error(_: Request, exc: HaClientError) -> JSONResponse:
|
|
return JSONResponse(
|
|
status_code=_status_code_for_ha_error(exc),
|
|
content={"detail": exc.public_detail},
|
|
)
|
|
|
|
|
|
def _status_code_for_ha_error(exc: HaClientError) -> int:
|
|
if isinstance(exc, HaTimeoutError):
|
|
return status.HTTP_504_GATEWAY_TIMEOUT
|
|
if isinstance(exc, (HaAuthError, HaHttpError)):
|
|
return status.HTTP_502_BAD_GATEWAY
|
|
return status.HTTP_502_BAD_GATEWAY
|