Skip to content

Commit fc43cf9

Browse files
Replace Exception with specific error types (#5755)
Replaces generic Exception raises with more specific error types such as RuntimeError, ValueError, NotImplementedError, ImportError, and custom exceptions across multiple modules. This improves error handling clarity and aligns with Python best practices for exception usage.
1 parent e34f258 commit fc43cf9

File tree

25 files changed

+84
-60
lines changed

25 files changed

+84
-60
lines changed

sdk/python/packages/flet-cli/src/flet_cli/utils/android_sdk.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44
from pathlib import Path
55
from typing import Optional
66

7+
from rich.progress import Progress
8+
79
from flet_cli.utils import processes
810
from flet_cli.utils.distros import download_with_progress, extract_with_progress
9-
from rich.progress import Progress
1011

1112
ANDROID_CMDLINE_TOOLS_DOWNLOAD_VERSION = "11076708"
1213
ANDROID_CMDLINE_TOOLS_VERSION = "12.0"
@@ -98,7 +99,7 @@ def cmdline_tools_url(self):
9899
},
99100
}[platform.system()][platform.machine()]
100101
except KeyError:
101-
raise Exception(
102+
raise RuntimeError(
102103
f"Unsupported platform: {platform.system()}-{platform.machine()}"
103104
) from None
104105

@@ -183,7 +184,7 @@ def _install_package(self, home_dir: Path, package_name: str) -> int:
183184
)
184185
if p.returncode != 0:
185186
self.log(p.stderr)
186-
raise Exception("Error installing Android SDK tools")
187+
raise RuntimeError("Error installing Android SDK tools")
187188
return 1
188189

189190
def _accept_licenses(self, home_dir: Path):
@@ -208,7 +209,7 @@ def _accept_licenses(self, home_dir: Path):
208209
)
209210
if p.returncode != 0:
210211
self.log(p.stderr)
211-
raise Exception("Error accepting Android SDK licenses")
212+
raise RuntimeError("Error accepting Android SDK licenses")
212213

213214
def get_installed_packages(self, home_dir: Path):
214215
self.log("Checking installed Android APIs and build tools")
@@ -219,7 +220,7 @@ def get_installed_packages(self, home_dir: Path):
219220
)
220221
if p.returncode != 0:
221222
self.log(p.stderr)
222-
raise Exception(
223+
raise RuntimeError(
223224
"Error retrieving the list of installed Android SDK packages"
224225
)
225226
return p.stdout

sdk/python/packages/flet-cli/src/flet_cli/utils/project_dependencies.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
def get_poetry_dependencies(
99
poetry_dependencies: Optional[dict[str, Any]] = None,
1010
) -> Optional[list[str]]:
11-
1211
if poetry_dependencies is None:
1312
return None
1413

@@ -51,8 +50,9 @@ def format_dependency_version(dependency_name: str, dependency_value: Any):
5150
dependency_name = ""
5251
sep = ""
5352
else:
54-
raise Exception(
55-
f"Unsupported dependency specification: {dependency_name} = {dependency_value}"
53+
raise ValueError(
54+
"Unsupported dependency specification: "
55+
f"{dependency_name} = {dependency_value}"
5656
)
5757

5858
# markers - common for all
@@ -88,7 +88,6 @@ def format_dependency_version(dependency_name: str, dependency_value: Any):
8888
def get_project_dependencies(
8989
project_dependencies: Optional[dict[str, Any]] = None,
9090
) -> Optional[list[str]]:
91-
9291
if project_dependencies is None:
9392
return None
9493

sdk/python/packages/flet-web/src/flet_web/fastapi/flet_app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ async def __on_message(self, data: Any):
325325

326326
else:
327327
# it's something else
328-
raise Exception(f'Unknown message "{action}": {body}')
328+
raise RuntimeError(f'Unknown message "{action}": {body}')
329329

330330
if task:
331331
self.__running_tasks.add(task)

sdk/python/packages/flet-web/src/flet_web/fastapi/flet_app_manager.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,10 @@
66
from datetime import datetime, timezone
77
from typing import Optional
88

9+
import flet_web.fastapi as flet_fastapi
910
from flet.messaging.connection import Connection
1011
from flet.messaging.session import Session
1112
from flet.pubsub.pubsub_hub import PubSubHub
12-
13-
import flet_web.fastapi as flet_fastapi
1413
from flet_web.fastapi.oauth_state import OAuthState
1514

1615
logger = logging.getLogger(flet_fastapi.__name__)
@@ -84,7 +83,7 @@ async def reconnect_session(self, session_id: str, conn: Connection):
8483
session = self.__sessions[session_id]
8584
await session.connect(conn)
8685
else:
87-
raise Exception(f"Session has expired or not found: {session_id}")
86+
raise RuntimeError(f"Session has expired or not found: {session_id}")
8887

8988
async def disconnect_session(self, session_id: str, session_timeout_seconds: int):
9089
logger.info(f"Session disconnected: {session_id}")

sdk/python/packages/flet-web/src/flet_web/fastapi/flet_static_files.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66
from typing import Optional
77

88
from fastapi.staticfiles import StaticFiles
9-
from flet.controls.types import RouteUrlStrategy, WebRenderer
10-
from flet.utils import Once, get_bool_env_var
119
from starlette.types import Receive, Scope, Send
1210

1311
import flet_web.fastapi as flet_fastapi
12+
from flet.controls.types import RouteUrlStrategy, WebRenderer
13+
from flet.utils import Once, get_bool_env_var
1414
from flet_web import (
1515
get_package_web_dir,
1616
patch_font_manifest_json,
@@ -120,7 +120,7 @@ async def __config(self, root_path: str):
120120
logger.info(f"Web root: {web_dir}")
121121

122122
if not os.path.exists(web_dir):
123-
raise Exception(f"Web root path not found: {web_dir}")
123+
raise RuntimeError(f"Web root path not found: {web_dir}")
124124

125125
# user-defined assets
126126
if self.__assets_dir:

sdk/python/packages/flet-web/src/flet_web/fastapi/flet_upload.py

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
from datetime import datetime, timezone
44
from typing import Optional
55

6-
import flet_web.fastapi as flet_fastapi
76
from anyio import open_file
8-
from fastapi import Request
7+
from fastapi import HTTPException, Request, status
8+
9+
import flet_web.fastapi as flet_fastapi
910
from flet_web.uploads import build_upload_query_string, get_upload_signature
1011

1112
logger = logging.getLogger(flet_fastapi.__name__)
@@ -18,7 +19,8 @@ class FletUpload:
1819
Parameters:
1920
2021
* `upload_dir` (str) - an absolute path to a directory with uploaded files.
21-
* `max_upload_size` (str, int) - maximum size of a single upload, bytes. Unlimited if `None`.
22+
* `max_upload_size` (str, int) - maximum size of a single upload, bytes.
23+
Unlimited if `None`.
2224
* `secret_key` (str, optional) - secret key to sign and verify upload requests.
2325
"""
2426

@@ -50,14 +52,24 @@ def __init__(
5052
"""
5153

5254
async def handle(self, request: Request):
53-
file_name = request.query_params["f"]
54-
expire_str = request.query_params["e"]
55-
signature = request.query_params["s"]
55+
query_params = request.query_params
56+
file_name = query_params.get("f")
57+
expire_str = query_params.get("e")
58+
signature = query_params.get("s")
5659

5760
if not file_name or not expire_str or not signature:
58-
raise Exception("Invalid request")
61+
raise HTTPException(
62+
status_code=status.HTTP_400_BAD_REQUEST,
63+
detail="Missing upload parameters",
64+
)
5965

60-
expire_date = datetime.fromisoformat(expire_str)
66+
try:
67+
expire_date = datetime.fromisoformat(expire_str)
68+
except ValueError as e:
69+
raise HTTPException(
70+
status_code=status.HTTP_400_BAD_REQUEST,
71+
detail="Invalid expiration parameter",
72+
) from e
6173

6274
# verify signature
6375
query_string = build_upload_query_string(file_name, expire_date)
@@ -67,17 +79,26 @@ async def handle(self, request: Request):
6779
)
6880
!= signature
6981
):
70-
raise Exception("Invalid request")
82+
raise HTTPException(
83+
status_code=status.HTTP_403_FORBIDDEN,
84+
detail="Invalid upload signature",
85+
)
7186

7287
# check expiration date
7388
if datetime.now(timezone.utc) >= expire_date:
74-
raise Exception("Invalid request")
89+
raise HTTPException(
90+
status_code=status.HTTP_410_GONE,
91+
detail="Upload URL has expired",
92+
)
7593

7694
# build/validate dest path
7795
joined_path = os.path.join(self.__upload_dir, file_name)
7896
full_path = os.path.realpath(joined_path)
7997
if os.path.commonpath([full_path, self.__upload_dir]) != self.__upload_dir:
80-
raise Exception("Invalid request")
98+
raise HTTPException(
99+
status_code=status.HTTP_400_BAD_REQUEST,
100+
detail="Invalid upload destination",
101+
)
81102

82103
# create directory if not exists
83104
dest_dir = os.path.dirname(full_path)
@@ -89,7 +110,8 @@ async def handle(self, request: Request):
89110
async for chunk in request.stream():
90111
size += len(chunk)
91112
if self.__max_upload_size and size > self.__max_upload_size:
92-
raise Exception(
93-
f"Max upload size reached: {self.__max_upload_size}"
113+
raise HTTPException(
114+
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
115+
detail="Max upload size exceeded",
94116
)
95117
await f.write(chunk)

sdk/python/packages/flet-web/src/flet_web/uploads.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,9 @@ def get_upload_signature(
3939
if env_secret_key:
4040
secret_key = env_secret_key
4141
if not secret_key:
42-
raise Exception(
43-
"Specify secret_key parameter or set FLET_SECRET_KEY environment variable to enable uploads."
42+
raise RuntimeError(
43+
"Specify secret_key parameter or set FLET_SECRET_KEY environment "
44+
"variable to enable uploads."
4445
)
4546
signing_key = hmac.new(
4647
secret_key.encode("utf-8"),
@@ -49,6 +50,6 @@ def get_upload_signature(
4950
).digest()
5051
return hmac.new(
5152
signing_key,
52-
f"{upload_endpoint_path.strip('/')}{query_string}".encode("utf-8"),
53+
f"{upload_endpoint_path.strip('/')}{query_string}".encode(),
5354
hashlib.sha256,
5455
).hexdigest()

sdk/python/packages/flet/docs/cookbook/authentication.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ def main(page: Page):
438438

439439
def on_login(e):
440440
if e.error:
441-
raise Exception(e.error)
441+
raise RuntimeError(e.error)
442442
print("User ID:", page.auth.user.id)
443443
print("Access token:", page.auth.token.access_token)
444444

sdk/python/packages/flet/src/flet/auth/authorization_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ async def __fetch_user_and_groups(self):
9090
self.user = await self.provider._fetch_user(self.__token.access_token)
9191
if self.user is None and self.provider.user_endpoint is not None:
9292
if self.provider.user_id_fn is None:
93-
raise Exception(
93+
raise ValueError(
9494
"user_id_fn must be specified too if user_endpoint is not None"
9595
)
9696
self.user = await self.__get_user()

sdk/python/packages/flet/src/flet/auth/oauth_provider.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def __init__(
3636
self.code_verifier = code_verifier
3737

3838
def _name(self):
39-
raise Exception("Not implemented")
39+
raise NotImplementedError("Subclasses must implement _name()")
4040

4141
async def _fetch_groups(self, access_token: str) -> list[Group]:
4242
return []

0 commit comments

Comments
 (0)