Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixup pylint broad exceptions warnings #3923

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ disable=missing-docstring,
unused-argument, # temp-pylint-upgrade
redefined-builtin,
cyclic-import,
broad-exception-raised,

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
Expand Down Expand Up @@ -481,3 +480,8 @@ max-statements=50

# Minimum number of public methods for a class (see R0903).
min-public-methods=2

[EXCEPTIONS]

# Exceptions that will emit a warning when being caught.
overgeneral-exceptions=builtins.Exception
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,10 @@ def _encode_attributes(
if attributes:
pb2_attributes = []
for key, value in attributes.items():
# pylint: disable=broad-exception-caught
try:
pb2_attributes.append(_encode_key_value(key, value))
except Exception as error: # pylint: disable=broad-except
except Exception as error:
_logger.exception(error)
else:
pb2_attributes = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ def test_constructors(self):
try:
json.ZipkinExporter()
http.ZipkinExporter()
except Exception as exc: # pylint: disable=broad-except
except Exception as exc: # pylint: disable=broad-exception-caught
self.assertIsNone(exc)
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def extract(
continue
try:
name, value = entry.split("=", 1)
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
_logger.warning(
"Baggage list-member `%s` doesn't match the format", entry
)
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-api/src/opentelemetry/context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def _load_runtime_context() -> _RuntimeContext:
)
)
).load()()
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
logger.exception(
"Failed to load context: %s, fallback to %s",
configured_context,
Expand Down Expand Up @@ -152,7 +152,7 @@ def detach(token: object) -> None:
"""
try:
_RUNTIME_CONTEXT.detach(token)
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
logger.exception("Failed to detach context")


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def inject(
raise ValueError(
f"Propagator {propagator} not found. It is either misspelled or not installed."
)
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
logger.exception("Failed to load propagator: %s", propagator)
raise

Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-api/src/opentelemetry/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ def use_span(
finally:
context_api.detach(token)

except Exception as exc: # pylint: disable=broad-except
except Exception as exc: # pylint: disable=broad-exception-caught
if isinstance(span, Span) and span.is_recording():
# Record the exception as an event
if record_exception:
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-api/src/opentelemetry/util/_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,6 @@ def _load_provider(
)
).load()(),
)
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
logger.exception("Failed to load configured provider %s", provider)
raise
2 changes: 1 addition & 1 deletion opentelemetry-api/tests/metrics/test_observation.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def test_measurement_init(self):

# float
Observation(321.321, {"hello": "world"})
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
self.fail(
"Unexpected exception raised when instantiating Observation"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ def _import_sampler(sampler_name: str) -> Optional[Sampler]:
_logger.warning(message)
raise ValueError(message)
return sampler
except Exception as exc: # pylint: disable=broad-except
except Exception as exc: # pylint: disable=broad-exception-caught
_logger.warning(
"Using default sampler. Failed to initialize sampler, %s: %s",
sampler_name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def emit(self, log_data: LogData):
token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True))
try:
self._exporter.export((log_data,))
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
_logger.exception("Exception while exporting logs.")
detach(token)

Expand Down Expand Up @@ -309,7 +309,7 @@ def _export_batch(self) -> int:
token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True))
try:
self._exporter.export(self._log_records[:idx]) # type: ignore
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
_logger.exception("Exception while exporting logs.")
detach(token)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def __exit__(self, exc_type, exc_value, traceback):
error_handler_class()._handle(exc_value)
plugin_handled = True

# pylint: disable=broad-except
# pylint: disable=broad-exception-caught
except Exception as error_handling_error:

logger.exception(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ def __init__(

with self._all_metric_readers_lock:
if metric_reader in self._all_metric_readers:
# pylint: disable=broad-exception-raised
raise Exception(
f"MetricReader {metric_reader} has been registered "
"already in other MeterProvider instance"
Expand Down Expand Up @@ -437,7 +438,7 @@ def force_flush(self, timeout_millis: float = 10_000) -> bool:
timeout_millis=(deadline_ns - current_ts) / 10**6
)

# pylint: disable=broad-except
# pylint: disable=broad-exception-caught
except Exception as error:

metric_reader_error[metric_reader] = error
Expand All @@ -451,6 +452,7 @@ def force_flush(self, timeout_millis: float = 10_000) -> bool:
]
)

# pylint: disable=broad-exception-raised
raise Exception(
"MeterProvider.force_flush failed because the following "
"metric readers failed during collect:\n"
Expand All @@ -476,14 +478,15 @@ def _shutdown():
current_ts = time_ns()
try:
if current_ts >= deadline_ns:
# pylint: disable=broad-exception-raised
raise Exception(
"Didn't get to execute, deadline already exceeded"
)
metric_reader.shutdown(
timeout_millis=(deadline_ns - current_ts) / 10**6
)

# pylint: disable=broad-except
# pylint: disable=broad-exception-caught
except Exception as error:

metric_reader_error[metric_reader] = error
Expand All @@ -501,6 +504,7 @@ def _shutdown():
]
)

# pylint: disable=broad-exception-raised
raise Exception(
(
"MeterProvider.shutdown failed because the following "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -988,6 +988,7 @@ def _downscale(change: int, positive, negative):
return

if change < 0:
# pylint: disable=broad-exception-raised
raise Exception("Invalid change of scale")

positive.downscale(change)
Expand Down Expand Up @@ -1025,6 +1026,7 @@ def _merge(
span = previous_buckets.index_end - index

if span >= self._max_size:
# pylint: disable=broad-exception-raised
raise Exception("Incorrect merge scale")

if span >= len(previous_buckets.counts):
Expand All @@ -1036,6 +1038,7 @@ def _merge(
span = index - previous_buckets.index_start

if span >= self._max_size:
# pylint: disable=broad-exception-raised
raise Exception("Incorrect merge scale")

if span >= len(previous_buckets.counts):
Expand Down Expand Up @@ -1152,6 +1155,7 @@ def _create_aggregation(
if isinstance(instrument, _Gauge):
return _LastValueAggregation(attributes)

# pylint: disable=broad-exception-raised
raise Exception(f"Invalid instrument type {type(instrument)} found")


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,11 @@ def _init(self, scale: int) -> None:
# pylint: disable=attribute-defined-outside-init

if scale > self._get_max_scale():
# pylint: disable=broad-exception-raised
raise Exception(f"scale is larger than {self._max_scale}")

if scale < self._get_min_scale():
# pylint: disable=broad-exception-raised
raise Exception(f"scale is smaller than {self._min_scale}")

# The size of the exponential histogram buckets is determined by a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def force_flush(self, timeout_millis: float = 10_000) -> bool:


class MetricReader(ABC):
# pylint: disable=too-many-branches
# pylint: disable=too-many-branches,broad-exception-raised
"""
Base class for all metric readers

Expand Down Expand Up @@ -529,12 +529,13 @@ def _receive_metrics(
) -> None:

token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True))
# pylint: disable=broad-exception-caught,invalid-name
try:
with self._export_lock:
self._exporter.export(
metrics_data, timeout_millis=timeout_millis
)
except Exception as e: # pylint: disable=broad-except,invalid-name
except Exception as e:
_logger.exception("Exception while exporting metrics %s", str(e))
detach(token)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,11 @@ def __init__(
result = self._check_name_unit_description(name, unit, description)

if result["name"] is None:
# pylint: disable=broad-exception-raised
raise Exception(_ERROR_MESSAGE.format(name))

if result["unit"] is None:
# pylint: disable=broad-exception-raised
raise Exception(_ERROR_MESSAGE.format(unit))

name = result["name"]
Expand Down Expand Up @@ -85,9 +87,11 @@ def __init__(
result = self._check_name_unit_description(name, unit, description)

if result["name"] is None:
# pylint: disable=broad-exception-raised
raise Exception(_ERROR_MESSAGE.format(name))

if result["unit"] is None:
# pylint: disable=broad-exception-raised
raise Exception(_ERROR_MESSAGE.format(unit))

name = result["name"]
Expand Down Expand Up @@ -136,7 +140,7 @@ def callback(
instrument=self,
attributes=api_measurement.attributes,
)
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
_logger.exception(
"Callback failed for instrument %s.", self.name
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ def __init__(
is meter_schema_url
is None
):
# pylint: disable=broad-exception-raised
raise Exception(
"Some instrument selection "
f"criteria must be provided for View {name}"
Expand All @@ -113,7 +114,7 @@ def __init__(
and instrument_name is not None
and ("*" in instrument_name or "?" in instrument_name)
):

# pylint: disable=broad-exception-raised
raise Exception(
f"View {name} declared with wildcard "
"characters in instrument_name"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def get_aggregated_resources(
detector,
timeout,
)
# pylint: disable=broad-except
# pylint: disable=broad-exception-caught
except Exception as ex:
if detector.raise_on_error:
raise ex
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def on_end(self, span: ReadableSpan) -> None:
token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True))
try:
self.span_exporter.export((span,))
# pylint: disable=broad-except
# pylint: disable=broad-exception-caught
except Exception:
logger.exception("Exception while exporting Span.")
detach(token)
Expand Down Expand Up @@ -365,7 +365,7 @@ def _export_batch(self) -> int:
# Ignore type b/c the Optional[None]+slicing is too "clever"
# for mypy
self.span_exporter.export(self.spans_list[:idx]) # type: ignore
except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
logger.exception("Exception while exporting Span batch.")
detach(token)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=broad-except

from logging import ERROR
from unittest import TestCase
Expand All @@ -30,6 +29,7 @@ def test_default_error_handler(self, mock_entry_points):

with self.assertLogs(logger, ERROR):
with GlobalErrorHandler():
# pylint: disable=broad-exception-raised
raise Exception("some exception")

# pylint: disable=no-self-use
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-sdk/tests/trace/test_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1969,7 +1969,7 @@ def test_parent_child_span_exception(self):
) as child_span:
raise exception

except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
pass

self.assertTrue(child_span.status.is_ok)
Expand Down Expand Up @@ -2014,7 +2014,7 @@ def test_child_parent_span_exception(self):
pass
raise exception

except Exception: # pylint: disable=broad-except
except Exception: # pylint: disable=broad-exception-caught
pass

self.assertTrue(child_span.status.is_ok)
Expand Down
1 change: 1 addition & 0 deletions shim/opentelemetry-opentracing-shim/tests/test_shim.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,7 @@ def test_span_on_error(self):
# Raise an exception while a span is active.
with self.assertRaises(Exception) as exc_ctx:
with self.shim.start_active_span("TestName") as scope:
# pylint: disable=broad-exception-raised
raise Exception("bad thing")

ex = exc_ctx.exception
Expand Down
6 changes: 3 additions & 3 deletions tests/opentelemetry-test-utils/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_no_exception(self):
with self.assertNotRaises(Exception):
pass

except Exception as error: # pylint: disable=broad-except
except Exception as error: # pylint: disable=broad-exception-caught

self.fail( # pylint: disable=no-member
f"Unexpected exception {error} was raised"
Expand All @@ -36,7 +36,7 @@ def test_no_specified_exception_single(self):
with self.assertNotRaises(KeyError):
1 / 0 # pylint: disable=pointless-statement

except Exception as error: # pylint: disable=broad-except
except Exception as error: # pylint: disable=broad-exception-caught

self.fail( # pylint: disable=no-member
f"Unexpected exception {error} was raised"
Expand All @@ -49,7 +49,7 @@ def test_no_specified_exception_multiple(self):
with self.assertNotRaises(KeyError, IndexError):
1 / 0 # pylint: disable=pointless-statement

except Exception as error: # pylint: disable=broad-except
except Exception as error: # pylint: disable=broad-exception-caught

self.fail( # pylint: disable=no-member
f"Unexpected exception {error} was raised"
Expand Down