From 6227bc3611fe7178698b5ec11e9d26340c3971df Mon Sep 17 00:00:00 2001 From: Yurii Motov Date: Mon, 14 Apr 2025 09:06:14 +0200 Subject: [PATCH] Allow passing a sequence of codes or exceptions to `exception_handler` --- fastapi/applications.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index 6d427cdc2..596f52bd0 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -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