Allow passing a sequence of codes or exceptions to `exception_handler`

This commit is contained in:
Yurii Motov 2025-04-14 09:06:14 +02:00
parent 4ec5e0a90a
commit 6227bc3611
1 changed files with 7 additions and 3 deletions

View File

@ -4540,10 +4540,10 @@ class FastAPI(Starlette):
def exception_handler(
self,
exc_class_or_status_code: Annotated[
Union[int, Type[Exception]],
Union[int, Type[Exception], Sequence[int], Sequence[Type[Exception]]],
Doc(
"""
The Exception class this would handle, or a status code.
The Exception class, a status code or a sequence of them this would handle.
"""
),
],
@ -4579,7 +4579,11 @@ class FastAPI(Starlette):
"""
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.add_exception_handler(exc_class_or_status_code, func)
if isinstance(exc_class_or_status_code, Sequence):
for exc_class_or_status_code_ in exc_class_or_status_code:
self.add_exception_handler(exc_class_or_status_code_, func)
else:
self.add_exception_handler(exc_class_or_status_code, func)
return func
return decorator