Skip to content

Commit ca6907d

Browse files
authored
Create handlers.py
1 parent 697c0f8 commit ca6907d

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

app/exceptions/handlers.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import re
2+
from fastapi import Request
3+
from fastapi.responses import JSONResponse
4+
from sqlalchemy.exc import IntegrityError
5+
6+
async def integrity_error_handler(request: Request, exc: IntegrityError):
7+
"""
8+
Trata IntegrityError e retorna:
9+
status_code: 303
10+
detail: "Já existe um atleta cadastrado com o cpf: x"
11+
Onde x é extraído da mensagem de erro quando possível.
12+
"""
13+
raw = ""
14+
try:
15+
raw = str(exc.orig) if exc.orig is not None else str(exc)
16+
except Exception:
17+
raw = str(exc)
18+
19+
# Tenta extrair padrão PostgreSQL: Key (cpf)=(123456) already exists.
20+
cpf_value = None
21+
match = re.search(r"Key\s*\((?P<col>[^)]+)\)=\((?P<val>[^)]+)\)", raw)
22+
if match:
23+
col = match.group("col")
24+
val = match.group("val")
25+
if "cpf" in col.lower():
26+
cpf_value = val
27+
28+
if not cpf_value:
29+
# tenta encontrar um trecho que pareça com CPF no texto
30+
m2 = re.search(r"(\d{9,14})", raw)
31+
if m2:
32+
cpf_value = m2.group(1)
33+
34+
if cpf_value:
35+
msg = f"Já existe um atleta cadastrado com o cpf: {cpf_value}"
36+
else:
37+
msg = "Violação de integridade de dados."
38+
39+
return JSONResponse(status_code=303, content={"detail": msg})

0 commit comments

Comments
 (0)