1- from collections . abc import Callable
2- from typing import Any , Type , Union
1+ from contextlib import contextmanager
2+ from typing import Generator
33
44from fastapi .exceptions import RequestValidationError
55from pydantic import ValidationError
66
77
8- class ensure_request_validation_errors ():
8+ @contextmanager
9+ def ensure_request_validation_errors () -> Generator [None , None , None ]:
910 """
1011 Converter for `ValidationError` to `RequestValidationError`.
1112
@@ -17,43 +18,14 @@ class ensure_request_validation_errors():
1718
1819 Usage examples:
1920
20- ```python
21- # Use as a decorator
22- @ensure_request_validation_errors
23- def some_func():
24- some_code_doing_extra_validation() # for example async validation
25- ```
26-
2721 ```python
2822 # Use as a context manager
2923 with ensure_request_validation_errors():
3024 some_code_doing_extra_validation() # for example async validation
3125 ```
3226 """
3327
34- func : Union [Callable , None ]
35-
36- def __init__ (self , func : Union [Callable , None ] = None ) -> None :
37- self .func = func
38-
39- def __call__ (self , * args : Any , ** kwargs : Any ) -> Any :
40- if self .func is None :
41- raise RuntimeError ("No func given" )
42-
43- with self :
44- return self .func (* args , ** kwargs )
45-
46- def __enter__ (self ) -> None :
47- pass
48-
49- def __exit__ (
50- self ,
51- exc_type : Union [Type [Exception ], None ],
52- exc_value : Union [Exception , None ],
53- traceback : Any ,
54- ) -> None :
55- if exc_value is None :
56- return
57-
58- if isinstance (exc_value , ValidationError ):
59- raise RequestValidationError (errors = exc_value .errors ())
28+ try :
29+ yield
30+ except ValidationError as O_o :
31+ raise RequestValidationError (errors = O_o .errors ())
0 commit comments