1+ from typing import Any
2+
13from fastapi import FastAPI
24from fastapi .exceptions import RequestValidationError
35from starlette .exceptions import HTTPException
46from starlette .requests import Request
57from starlette .responses import JSONResponse
68
9+ from conduit .core .utils .errors import format_errors
10+
711
812class BaseInternalException (Exception ):
913 """
@@ -12,12 +16,13 @@ class BaseInternalException(Exception):
1216
1317 _status_code = 0
1418 _message = ""
19+ _errors : dict = {}
1520
1621 def __init__ (
1722 self ,
1823 status_code : int | None = None ,
1924 message : str | None = None ,
20- errors : list [str ] | None = None ,
25+ errors : dict [str , dict [ Any , Any ] ] | None = None ,
2126 ) -> None :
2227 self .status_code = status_code
2328 self .message = message
@@ -29,6 +34,9 @@ def get_status_code(self) -> int:
2934 def get_message (self ) -> str :
3035 return self .message or self ._message
3136
37+ def get_errors (self ) -> dict [str , dict [Any , Any ]]:
38+ return self .errors or self ._errors
39+
3240 @classmethod
3341 def get_response (cls ) -> JSONResponse :
3442 return JSONResponse (
@@ -38,6 +46,7 @@ def get_response(cls) -> JSONResponse:
3846 "status_code" : cls ._status_code ,
3947 "type" : cls .__name__ ,
4048 "message" : cls ._message ,
49+ "errors" : cls ._errors ,
4150 },
4251 )
4352
@@ -96,20 +105,26 @@ class EmailAlreadyTakenException(BaseInternalException):
96105
97106 _status_code = 400
98107 _message = "User with this email already exists."
108+ _errors = {"email" : ["user with this email already exists." ]}
99109
100110
101111class UserNameAlreadyTakenException (BaseInternalException ):
102112 """Exception raised when username was found in database while registration."""
103113
104114 _status_code = 400
105115 _message = "User with this username already exists."
116+ _errors = {"username" : ["user with this username already exists." ]}
106117
107118
108119class IncorrectLoginInputException (BaseInternalException ):
109120 """Exception raised when email or password was incorrect while login."""
110121
111122 _status_code = 400
112123 _message = "Incorrect email or password."
124+ _errors = {
125+ "email" : ["incorrect email or password." ],
126+ "password" : ["incorrect email or password." ],
127+ }
113128
114129
115130class IncorrectJWTTokenException (BaseInternalException ):
@@ -170,6 +185,7 @@ async def _exception_handler(
170185 "status_code" : exc .get_status_code (),
171186 "type" : type (exc ).__name__ ,
172187 "message" : exc .get_message (),
188+ "errors" : exc .get_errors (),
173189 },
174190 )
175191
@@ -190,7 +206,7 @@ async def _exception_handler(
190206 "status_code" : 422 ,
191207 "type" : "RequestValidationError" ,
192208 "message" : "Schema validation error" ,
193- "errors" : exc .errors (),
209+ "errors" : format_errors ( errors = exc .errors () ),
194210 },
195211 )
196212
0 commit comments