Skip to content

Commit cc901cd

Browse files
Taragolispotiukuranusjr
authored
Replace to broad exceptions into the dev (#38489)
* Replace to broad exceptions into the Dev * Add changes according to the review Co-authored-by: Jarek Potiuk <[email protected]> Co-authored-by: Tzu-ping Chung <[email protected]> * RuntimeError -> SystemExit if detect it run in __main__ Co-authored-by: Tzu-ping Chung <[email protected]> --------- Co-authored-by: Jarek Potiuk <[email protected]> Co-authored-by: Tzu-ping Chung <[email protected]>
1 parent 0e1a789 commit cc901cd

20 files changed

+46
-52
lines changed

dev/breeze/src/airflow_breeze/commands/release_management_commands.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1143,7 +1143,7 @@ def _get_all_providers_in_dist(
11431143
for file in DIST_DIR.glob(f"{filename_prefix}*.tar.gz"):
11441144
matched = filename_pattern.match(file.name)
11451145
if not matched:
1146-
raise Exception(f"Cannot parse provider package name from {file.name}")
1146+
raise SystemExit(f"Cannot parse provider package name from {file.name}")
11471147
provider_package_id = matched.group(1).replace("_", ".")
11481148
yield provider_package_id
11491149

@@ -1168,7 +1168,7 @@ def get_all_providers_in_dist(package_format: str, install_selected_providers: s
11681168
)
11691169
)
11701170
else:
1171-
raise Exception(f"Unknown package format {package_format}")
1171+
raise SystemExit(f"Unknown package format {package_format}")
11721172
if install_selected_providers:
11731173
filter_list = install_selected_providers.split(",")
11741174
return [provider for provider in all_found_providers if provider in filter_list]
@@ -1293,11 +1293,12 @@ def install_provider_packages(
12931293
if dependency not in chunk:
12941294
chunk.append(dependency)
12951295
if len(list_of_all_providers) != total_num_providers:
1296-
raise Exception(
1296+
msg = (
12971297
f"Total providers {total_num_providers} is different "
12981298
f"than {len(list_of_all_providers)} (just to be sure"
12991299
f" no rounding errors crippled in)"
13001300
)
1301+
raise RuntimeError(msg)
13011302
parallelism = min(parallelism, len(provider_chunks))
13021303
with ci_group(f"Installing providers in {parallelism} chunks"):
13031304
all_params = [f"Chunk {n}" for n in range(parallelism)]

dev/breeze/src/airflow_breeze/global_constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ def get_airflow_version():
364364
airflow_version = line.split()[2][1:-1]
365365
break
366366
if airflow_version == "unknown":
367-
raise Exception("Unable to determine Airflow version")
367+
raise RuntimeError("Unable to determine Airflow version")
368368
return airflow_version
369369

370370

dev/breeze/src/airflow_breeze/utils/docs_publisher.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,19 @@ def _build_dir(self) -> str:
5858
@property
5959
def _current_version(self):
6060
if not self.is_versioned:
61-
raise Exception("This documentation package is not versioned")
61+
msg = (
62+
"This documentation package is not versioned. "
63+
"Make sure to add version in `provider.yaml` for the package."
64+
)
65+
raise RuntimeError(msg)
6266
if self.package_name == "apache-airflow":
6367
return get_airflow_version()
6468
if self.package_name.startswith("apache-airflow-providers-"):
6569
provider = get_provider_packages_metadata().get(get_short_package_name(self.package_name))
6670
return provider["versions"][0]
6771
if self.package_name == "helm-chart":
6872
return chart_version()
69-
return Exception(f"Unsupported package: {self.package_name}")
73+
raise SystemExit(f"Unsupported package: {self.package_name}")
7074

7175
@property
7276
def _publish_dir(self) -> str:

dev/breeze/src/airflow_breeze/utils/kubernetes_utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,8 @@ def get_architecture_string_for_urls() -> str:
9292
return "amd64"
9393
if architecture == Architecture.ARM:
9494
return "arm64"
95-
raise Exception(f"The architecture {architecture} is not supported when downloading kubernetes tools!")
95+
msg = f"The architecture {architecture} is not supported when downloading kubernetes tools!"
96+
raise SystemExit(msg)
9697

9798

9899
def _download_with_retries(num_tries, path, tool, url):

dev/breeze/src/airflow_breeze/utils/packages.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,9 @@ def refresh_provider_metadata_from_yaml_file(provider_yaml_path: Path):
132132

133133
try:
134134
jsonschema.validate(provider, schema=schema)
135-
except jsonschema.ValidationError:
136-
raise Exception(f"Unable to parse: {provider_yaml_path}.")
135+
except jsonschema.ValidationError as ex:
136+
msg = f"Unable to parse: {provider_yaml_path}. Original error {type(ex).__name__}: {ex}"
137+
raise RuntimeError(msg)
137138
except ImportError:
138139
# we only validate the schema if jsonschema is available. This is needed for autocomplete
139140
# to not fail with import error if jsonschema is not installed
@@ -176,12 +177,12 @@ def validate_provider_info_with_runtime_schema(provider_info: dict[str, Any]) ->
176177
try:
177178
jsonschema.validate(provider_info, schema=schema)
178179
except jsonschema.ValidationError as ex:
179-
get_console().print("[red]Provider info not validated against runtime schema[/]")
180-
raise Exception(
181-
"Error when validating schema. The schema must be compatible with "
182-
"airflow/provider_info.schema.json.",
183-
ex,
180+
get_console().print(
181+
"[red]Error when validating schema. The schema must be compatible with "
182+
"[bold]'airflow/provider_info.schema.json'[/bold].\n"
183+
f"Original exception [bold]{type(ex).__name__}: {ex}[/]"
184184
)
185+
raise SystemExit(1)
185186

186187

187188
def get_provider_info_dict(provider_id: str) -> dict[str, Any]:

docs/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@
7272
if provider_yaml["package-name"] == PACKAGE_NAME
7373
)
7474
except StopIteration:
75-
raise Exception(f"Could not find provider.yaml file for package: {PACKAGE_NAME}")
75+
raise RuntimeError(f"Could not find provider.yaml file for package: {PACKAGE_NAME}")
7676
PACKAGE_DIR = pathlib.Path(CURRENT_PROVIDER["package-dir"])
7777
PACKAGE_VERSION = CURRENT_PROVIDER["versions"][0]
7878
SYSTEM_TESTS_DIR = CURRENT_PROVIDER["system-tests-dir"]

docs/exts/docs_build/docs_builder.py

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333
PROCESS_TIMEOUT,
3434
)
3535
from docs.exts.docs_build.errors import DocBuildError, parse_sphinx_warnings
36-
from docs.exts.docs_build.helm_chart_utils import chart_version
3736
from docs.exts.docs_build.spelling_checks import SpellingError, parse_spelling_warnings
3837

3938
console = Console(force_terminal=True, color_system="standard", width=CONSOLE_WIDTH)
@@ -88,21 +87,6 @@ def log_build_warning_filename(self) -> str:
8887
"""Warnings from build job."""
8988
return os.path.join(self._build_dir, f"warning-build-{self.package_name}.log")
9089

91-
@property
92-
def _current_version(self):
93-
if not self.is_versioned:
94-
raise Exception("This documentation package is not versioned")
95-
if self.package_name == "apache-airflow":
96-
from airflow.version import version as airflow_version
97-
98-
return airflow_version
99-
if self.package_name.startswith("apache-airflow-providers-"):
100-
provider = next(p for p in ALL_PROVIDER_YAMLS if p["package-name"] == self.package_name)
101-
return provider["versions"][0]
102-
if self.package_name == "helm-chart":
103-
return chart_version()
104-
return Exception(f"Unsupported package: {self.package_name}")
105-
10690
@property
10791
def _src_dir(self) -> str:
10892
return f"{DOCS_DIR}/{self.package_name}"

docs/exts/operators_and_hooks_ref.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,10 @@ def _render_template(template_name, **kwargs):
6969

7070
def _docs_path(filepath: str):
7171
if not filepath.startswith("/docs/"):
72-
raise Exception(f"The path must starts with '/docs/'. Current value: {filepath}")
72+
raise RuntimeError(f"The path must starts with '/docs/'. Current value: {filepath}")
7373

7474
if not filepath.endswith(".rst"):
75-
raise Exception(f"The path must ends with '.rst'. Current value: {filepath}")
75+
raise RuntimeError(f"The path must ends with '.rst'. Current value: {filepath}")
7676

7777
if filepath.startswith("/docs/apache-airflow-providers-"):
7878
_, _, provider, rest = filepath.split("/", maxsplit=3)

docs/exts/provider_yaml_utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,9 @@ def load_package_data(include_suspended: bool = False) -> list[dict[str, Any]]:
6767
provider = yaml.safe_load(yaml_file)
6868
try:
6969
jsonschema.validate(provider, schema=schema)
70-
except jsonschema.ValidationError:
71-
raise Exception(f"Unable to parse: {provider_yaml_path}.")
70+
except jsonschema.ValidationError as ex:
71+
msg = f"Unable to parse: {provider_yaml_path}. Original error {type(ex).__name__}: {ex}"
72+
raise RuntimeError(msg)
7273
if provider["state"] == "suspended" and not include_suspended:
7374
continue
7475
provider_yaml_dir = os.path.dirname(provider_yaml_path)

hatch_build.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -592,11 +592,12 @@ def get_provider_requirement(provider_spec: str) -> str:
592592
if PROVIDER_DEPENDENCIES[provider_id]["state"] not in ["ready", "suspended", "removed"]:
593593
for dependency in PROVIDER_DEPENDENCIES[provider_id]["deps"]:
594594
if dependency.startswith("apache-airflow-providers"):
595-
raise Exception(
595+
msg = (
596596
f"The provider {provider_id} is pre-installed and it has as dependency "
597597
f"to another provider {dependency}. This is not allowed. Pre-installed"
598598
f"providers should only have 'apache-airflow' and regular dependencies."
599599
)
600+
raise SystemExit(msg)
600601
if not dependency.startswith("apache-airflow"):
601602
PREINSTALLED_NOT_READY_DEPS.append(dependency)
602603

scripts/ci/pre_commit/generate_pypi_readme.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def extract_section(content, section_name):
5454
if section_match:
5555
return section_match.group(1)
5656
else:
57-
raise Exception(f"Cannot find section {section_name} in README.md")
57+
raise RuntimeError(f"Cannot find section {section_name} in README.md")
5858

5959

6060
if __name__ == "__main__":

scripts/ci/pre_commit/insert_extras.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def get_header_and_footer(extra_type: str, file_format: str) -> tuple[str, str]:
4242
elif file_format == "txt":
4343
return f"# START {extra_type.upper()} HERE", f"# END {extra_type.upper()} HERE"
4444
else:
45-
raise Exception(f"Bad format {format} passed. Only rst and txt are supported")
45+
raise ValueError(f"Bad format {format} passed. Only rst and txt are supported")
4646

4747

4848
def get_wrapped_list(extras_set: list[str]) -> list[str]:
@@ -81,7 +81,7 @@ def process_documentation_files() -> bool:
8181
extra_type_dict = get_extra_types_dict()
8282
for file, file_format, add_comment in FILES_TO_UPDATE:
8383
if not file.exists():
84-
raise Exception(f"File {file} does not exist")
84+
raise FileNotFoundError(f"File {file} does not exist")
8585
for extra_type_description, extra_list in extra_type_dict.items():
8686
header, footer = get_header_and_footer(extra_type_description, file_format)
8787
if insert_documentation(

scripts/ci/pre_commit/json_schema.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from jsonschema.validators import extend, validator_for
3131

3232
if __name__ != "__main__":
33-
raise Exception(
33+
raise SystemExit(
3434
"This file is intended to be executed as an executable program. You cannot use it as a module."
3535
"To run this script, run the ./build_docs.py command"
3636
)
@@ -150,7 +150,7 @@ def _load_spec(spec_file: str | None, spec_url: str | None):
150150
if spec_url:
151151
spec_file = fetch_and_cache(url=spec_url, output_filename=re.sub(r"[^a-zA-Z0-9]", "-", spec_url))
152152
if not spec_file:
153-
raise Exception(f"The {spec_file} was None and {spec_url} did not lead to any file loading.")
153+
raise ValueError(f"The {spec_file} was None and {spec_url} did not lead to any file loading.")
154154
with open(spec_file) as schema_file:
155155
schema = json.loads(schema_file.read())
156156
return schema

scripts/ci/pre_commit/replace_bad_characters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from rich.console import Console
2626

2727
if __name__ != "__main__":
28-
raise Exception(
28+
raise SystemExit(
2929
"This file is intended to be executed as an executable program. You cannot use it as a module."
3030
f"To run this script, run the {__file__} command"
3131
)

scripts/ci/pre_commit/update_chart_dependencies.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def get_latest_prometheus_statsd_exporter_version() -> str:
3636
for version in quay_data["tags"]:
3737
if version["name"].startswith("v"):
3838
return version["name"]
39-
raise Exception("ERROR! No version found")
39+
raise RuntimeError("ERROR! No version found")
4040

4141

4242
if __name__ == "__main__":
@@ -64,7 +64,7 @@ def get_latest_prometheus_statsd_exporter_version() -> str:
6464
next_line = f" tag: {latest_prometheus_statsd_exporter_version}"
6565
replace = False
6666
else:
67-
raise Exception(
67+
raise ValueError(
6868
f"ERROR! The next line after repository: should be tag: - "
6969
f"index {index} in {VALUES_YAML_FILE}"
7070
)

scripts/ci/pre_commit/update_versions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def update_version(pattern: re.Pattern, v: str, file_path: Path):
3131
with file_path.open("r+") as f:
3232
file_content = f.read()
3333
if not pattern.search(file_content):
34-
raise Exception(f"Pattern {pattern!r} doesn't found in {file_path!r} file")
34+
raise RuntimeError(f"Pattern {pattern!r} doesn't found in {file_path!r} file")
3535
new_content = pattern.sub(rf"\g<1>{v}\g<2>", file_content)
3636
if file_content == new_content:
3737
return

scripts/in_container/run_provider_yaml_files_check.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@
6262
from yaml import SafeLoader # type: ignore
6363

6464
if __name__ != "__main__":
65-
raise Exception(
65+
raise SystemExit(
6666
"This file is intended to be executed as an executable program. You cannot use it as a module."
6767
)
6868

@@ -112,8 +112,9 @@ def _load_package_data(package_paths: Iterable[str]):
112112
rel_path = pathlib.Path(provider_yaml_path).relative_to(ROOT_DIR).as_posix()
113113
try:
114114
jsonschema.validate(provider, schema=schema)
115-
except jsonschema.ValidationError:
116-
raise Exception(f"Unable to parse: {rel_path}.")
115+
except jsonschema.ValidationError as ex:
116+
msg = f"Unable to parse: {provider_yaml_path}. Original error {type(ex).__name__}: {ex}"
117+
raise RuntimeError(msg)
117118
if not provider["state"] == "suspended":
118119
result[rel_path] = provider
119120
else:

scripts/in_container/update_quarantined_test_status.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,14 +202,14 @@ def get_table(history_map: dict[str, TestHistory]) -> str:
202202
print(f"Token: {token}")
203203
github_repository = os.environ.get("GITHUB_REPOSITORY")
204204
if not github_repository:
205-
raise Exception("GitHub Repository must be defined!")
205+
raise RuntimeError("GitHub Repository must be defined!")
206206
user, repo = github_repository.split("/")
207207
print(f"User: {user}, Repo: {repo}")
208208
issue_id = int(os.environ.get("ISSUE_ID", 0))
209209
num_runs = int(os.environ.get("NUM_RUNS", 10))
210210

211211
if issue_id == 0:
212-
raise Exception("You need to define ISSUE_ID as environment variable")
212+
raise RuntimeError("You need to define ISSUE_ID as environment variable")
213213

214214
gh = login(token=token)
215215

scripts/tools/check_if_limited_dependencies.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
program = f"./{__file__}" if not __file__.startswith("./") else __file__
2828

2929
if __name__ != "__main__":
30-
raise Exception(
30+
raise SystemExit(
3131
"This file is intended to be used as an executable program. You cannot use it as a module."
3232
f"To execute this script, run the '{program}' command"
3333
)

scripts/tools/list-integrations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
program = f"./{__file__}" if not __file__.startswith("./") else __file__
3535

3636
if __name__ != "__main__":
37-
raise Exception(
37+
raise SystemExit(
3838
"This file is intended to be used as an executable program. You cannot use it as a module."
3939
f"To execute this script, run the '{program}' command"
4040
)

0 commit comments

Comments
 (0)