|
| 1 | +from functools import wraps |
| 2 | +from inspect import signature |
| 3 | +from typing import Any |
| 4 | +from typing import Callable |
| 5 | +from typing import Optional |
| 6 | +from typing import Type |
| 7 | + |
| 8 | +from openapi_core.exceptions import OpenAPIError |
| 9 | +from openapi_core.unmarshalling.schemas.exceptions import ValidateError |
| 10 | + |
| 11 | +OpenAPIErrorType = Type[OpenAPIError] |
| 12 | + |
| 13 | + |
| 14 | +class ValidationErrorWrapper: |
| 15 | + def __init__( |
| 16 | + self, |
| 17 | + err_cls: OpenAPIErrorType, |
| 18 | + err_validate_cls: Optional[OpenAPIErrorType] = None, |
| 19 | + err_cls_init: Optional[str] = None, |
| 20 | + **err_cls_kw: Any |
| 21 | + ): |
| 22 | + self.err_cls = err_cls |
| 23 | + self.err_validate_cls = err_validate_cls or err_cls |
| 24 | + self.err_cls_init = err_cls_init |
| 25 | + self.err_cls_kw = err_cls_kw |
| 26 | + |
| 27 | + def __call__(self, f: Callable[..., Any]) -> Callable[..., Any]: |
| 28 | + @wraps(f) |
| 29 | + def wrapper(*args: Any, **kwds: Any) -> Any: |
| 30 | + try: |
| 31 | + return f(*args, **kwds) |
| 32 | + except ValidateError as exc: |
| 33 | + self._raise_error(exc, self.err_validate_cls, f, *args, **kwds) |
| 34 | + except OpenAPIError as exc: |
| 35 | + self._raise_error(exc, self.err_cls, f, *args, **kwds) |
| 36 | + |
| 37 | + return wrapper |
| 38 | + |
| 39 | + def _raise_error( |
| 40 | + self, |
| 41 | + exc: OpenAPIError, |
| 42 | + cls: OpenAPIErrorType, |
| 43 | + f: Callable[..., Any], |
| 44 | + *args: Any, |
| 45 | + **kwds: Any |
| 46 | + ) -> None: |
| 47 | + if isinstance(exc, self.err_cls): |
| 48 | + raise |
| 49 | + sig = signature(f) |
| 50 | + ba = sig.bind(*args, **kwds) |
| 51 | + kw = { |
| 52 | + name: ba.arguments[func_kw] |
| 53 | + for name, func_kw in self.err_cls_kw.items() |
| 54 | + } |
| 55 | + init = cls |
| 56 | + if self.err_cls_init is not None: |
| 57 | + init = getattr(cls, self.err_cls_init) |
| 58 | + raise init(**kw) from exc |
0 commit comments