22
33from fastapi import FastAPI
44from fastapi .exceptions import RequestValidationError
5+ from pydantic import EnumError , StrRegexError
56from starlette .exceptions import HTTPException as StarletteHTTPException
67from starlette .requests import Request
78
@@ -19,38 +20,38 @@ def parse_error(
1920 :param raw: Whether this is a raw error or wrapped pydantic error
2021 :return: dict with name of the field (or "__all__") and actual message
2122 """
22- if err .type_ == "value_error.str.regex" :
23- message = "Provided value doesn't match valid format."
24- elif err .type_ == "type_error.enum" :
23+
24+ if isinstance (err .exc , EnumError ):
2525 message = "One or more values provided are not valid."
26+ elif isinstance (err .exc , StrRegexError ):
27+ message = "Provided value doesn't match valid format."
2628 else :
27- message = err .msg or ""
29+ message = str ( err .exc ) or ""
2830
29- if err .type_ . startswith ("value_error. error_code" ):
30- error_code = int (err .type_ .split ("." )[- 1 ])
31+ if hasattr ( err .exc , "code" ) and err . exc . code . startswith ("error_code" ):
32+ error_code = int (err .exc . code .split ("." )[- 1 ])
3133 else :
3234 # default error code for non-custom errors is 400
3335 error_code = 400
3436
3537 if not raw :
36- if len (err .loc ) == 2 :
37- if str (err .loc [0 ]) in ["body" , "query" ]:
38- name = err .loc [1 ]
38+ if len (err .loc_tuple () ) == 2 :
39+ if str (err .loc_tuple () [0 ]) in ["body" , "query" ]:
40+ name = err .loc_tuple () [1 ]
3941 else :
40- name = err .loc [0 ]
41- elif len (err .loc ) == 1 :
42- if str (err .loc [0 ]) == "body" :
42+ name = err .loc_tuple () [0 ]
43+ elif len (err .loc_tuple () ) == 1 :
44+ if str (err .loc_tuple () [0 ]) == "body" :
4345 name = "__all__"
4446 else :
45- name = str (err .loc [0 ])
47+ name = str (err .loc_tuple () [0 ])
4648 else :
4749 name = "__all__"
4850 else :
49- if len (err .loc ) == 2 :
50- name = str (err .loc [0 ])
51- # message = f"{str(err.loc[1]).lower()}: {message}"
52- elif len (err .loc ) == 1 :
53- name = str (err .loc [0 ])
51+ if len (err .loc_tuple ()) == 2 :
52+ name = str (err .loc_tuple ()[0 ])
53+ elif len (err .loc_tuple ()) == 1 :
54+ name = str (err .loc_tuple ()[0 ])
5455 else :
5556 name = "__all__"
5657
0 commit comments