diff --git a/osm_fieldwork/OdkCentral.py b/osm_fieldwork/OdkCentral.py index 39bf5ca72..0c8341d4e 100755 --- a/osm_fieldwork/OdkCentral.py +++ b/osm_fieldwork/OdkCentral.py @@ -185,18 +185,24 @@ def authenticate( self.session.headers.update({"accept": "odkcentral"}) # Get a session token - response = self.session.post( - f"{self.base}sessions", - json={ - "email": self.user, - "password": self.passwd, - }, - ) + try: + response = self.session.post( + f"{self.base}sessions", + json={ + "email": self.user, + "password": self.passwd, + }, + ) + except requests.exceptions.ConnectionError as request_error: + # URL does not exist + raise ConnectionError("Failed to connect to Central. Is the URL valid?") from request_error + if response.status_code == 401: # Unauthorized, invalid credentials - raise ValueError("ODK credentials are invalid, or may have been updated. Please update them.") + raise ConnectionError("ODK credentials are invalid, or may have changed. Please update them.") from None elif not response.ok: - response.raise_for_status() # Handle other errors + # Handle other errors + response.raise_for_status() self.session.headers.update({"Authorization": f"Bearer {response.json().get('token')}"}) diff --git a/osm_fieldwork/OdkCentralAsync.py b/osm_fieldwork/OdkCentralAsync.py index e7c6c0ed2..8290305ae 100755 --- a/osm_fieldwork/OdkCentralAsync.py +++ b/osm_fieldwork/OdkCentralAsync.py @@ -90,9 +90,18 @@ async def __aexit__(self, exc_type, exc_value, traceback): async def authenticate(self): """Authenticate to an ODK Central server.""" - async with self.session.post(f"{self.base}sessions", json={"email": self.user, "password": self.passwd}) as response: - token = (await response.json())["token"] - self.session.headers.update({"Authorization": f"Bearer {token}"}) + try: + async with self.session.post(f"{self.base}sessions", json={"email": self.user, "password": self.passwd}) as response: + token = (await response.json())["token"] + self.session.headers.update({"Authorization": f"Bearer {token}"}) + except aiohttp.ClientConnectorError as request_error: + await self.session.close() + raise ConnectionError("Failed to connect to Central. Is the URL valid?") from request_error + except aiohttp.ClientResponseError as response_error: + await self.session.close() + if response_error.status == 401: + raise ConnectionError("ODK credentials are invalid, or may have changed. Please update them.") from response_error + raise response_error class OdkProject(OdkCentral):