|
# retoor <retoor@molodetz.nl>
|
|
|
|
from fastapi import HTTPException
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from devplacepy_services.base.schemas import ErrorOut
|
|
|
|
|
|
def error_response(status_code: int, message: str, code: str) -> JSONResponse:
|
|
return JSONResponse(
|
|
ErrorOut(error=message, code=code).model_dump(),
|
|
status_code=status_code,
|
|
)
|
|
|
|
|
|
def http_error(status_code: int, message: str, code: str) -> HTTPException:
|
|
return HTTPException(
|
|
status_code=status_code,
|
|
detail=ErrorOut(error=message, code=code).model_dump(),
|
|
)
|
|
|
|
|
|
def error_code_for_status(status_code: int) -> str:
|
|
if status_code == 404:
|
|
return "not_found"
|
|
if status_code == 401:
|
|
return "unauthorized"
|
|
if status_code == 403:
|
|
return "forbidden"
|
|
if status_code == 422:
|
|
return "validation_error"
|
|
if status_code >= 500:
|
|
return "internal_error"
|
|
return "error"
|
|
|
|
|
|
def error_message_for_status(status_code: int, detail: str | None = None) -> str:
|
|
if status_code == 404:
|
|
return "Not found"
|
|
if status_code == 401:
|
|
return "Unauthorized"
|
|
if status_code == 403:
|
|
return "Forbidden"
|
|
if status_code >= 500:
|
|
return "Internal server error"
|
|
if detail:
|
|
return detail
|
|
return "Request failed"
|
|
|
|
|
|
def sanitize_detail(detail: object, status_code: int = 400) -> tuple[str, str]:
|
|
if isinstance(detail, dict):
|
|
if "error" in detail and "code" in detail:
|
|
return str(detail["error"]), str(detail["code"])
|
|
if "message" in detail:
|
|
return str(detail["message"]), error_code_for_status(status_code)
|
|
if isinstance(detail, list):
|
|
return "Validation failed", "validation_error"
|
|
if isinstance(detail, str):
|
|
return error_message_for_status(status_code, detail), error_code_for_status(status_code)
|
|
if detail is None:
|
|
return error_message_for_status(status_code), error_code_for_status(status_code)
|
|
return error_message_for_status(status_code, str(detail)), error_code_for_status(status_code) |