diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index 475f4bfa99..3c8a47d076 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -1061,10 +1061,16 @@ async def connect(self, handler: Optional[_MongoClientErrorHandler] = None) -> A reason=_verbose_connection_error_reason(ConnectionClosedReason.ERROR), error=ConnectionClosedReason.ERROR, ) - self._handle_connection_error(error) if isinstance(error, (IOError, OSError, *SSLErrors)): details = _get_timeout_details(self.opts) - _raise_connection_failure(self.address, error, timeout_details=details) + # Wrap to AutoReconnect/NetworkTimeout BEFORE labeling so the + # SystemOverloadedError label lands on the propagated exception. + try: + _raise_connection_failure(self.address, error, timeout_details=details) + except (AutoReconnect, NetworkTimeout) as wrapped: + self._handle_connection_error(wrapped) + raise + self._handle_connection_error(error) raise conn = AsyncConnection(networking_interface, self, self.address, conn_id, self.is_sdam) # type: ignore[arg-type] diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index 938eca42bd..11bfbba2ec 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -1057,10 +1057,16 @@ def connect(self, handler: Optional[_MongoClientErrorHandler] = None) -> Connect reason=_verbose_connection_error_reason(ConnectionClosedReason.ERROR), error=ConnectionClosedReason.ERROR, ) - self._handle_connection_error(error) if isinstance(error, (IOError, OSError, *SSLErrors)): details = _get_timeout_details(self.opts) - _raise_connection_failure(self.address, error, timeout_details=details) + # Wrap to AutoReconnect/NetworkTimeout BEFORE labeling so the + # SystemOverloadedError label lands on the propagated exception. + try: + _raise_connection_failure(self.address, error, timeout_details=details) + except (AutoReconnect, NetworkTimeout) as wrapped: + self._handle_connection_error(wrapped) + raise + self._handle_connection_error(error) raise conn = Connection(networking_interface, self, self.address, conn_id, self.is_sdam) # type: ignore[arg-type]