refactor: replace try-except blocks with contextlib.suppress for cleaner exception handling (#24284)

This commit is contained in:
Guangdong Liu
2025-08-21 18:18:49 +08:00
committed by GitHub
parent ad8e82ee1d
commit 1abf1240b2
16 changed files with 52 additions and 88 deletions

View File

@@ -1,4 +1,5 @@
import base64
import contextlib
import enum
from collections.abc import Mapping
from enum import Enum
@@ -227,10 +228,8 @@ class ToolInvokeMessage(BaseModel):
@classmethod
def decode_blob_message(cls, v):
if isinstance(v, dict) and "blob" in v:
try:
with contextlib.suppress(Exception):
v["blob"] = base64.b64decode(v["blob"])
except Exception:
pass
return v
@field_serializer("message")

View File

@@ -1,3 +1,4 @@
import contextlib
import json
from collections.abc import Generator, Iterable
from copy import deepcopy
@@ -69,10 +70,8 @@ class ToolEngine:
if parameters and len(parameters) == 1:
tool_parameters = {parameters[0].name: tool_parameters}
else:
try:
with contextlib.suppress(Exception):
tool_parameters = json.loads(tool_parameters)
except Exception:
pass
if not isinstance(tool_parameters, dict):
raise ValueError(f"tool_parameters should be a dict, but got a string: {tool_parameters}")
@@ -270,14 +269,12 @@ class ToolEngine:
if response.meta.get("mime_type"):
mimetype = response.meta.get("mime_type")
else:
try:
with contextlib.suppress(Exception):
url = URL(cast(ToolInvokeMessage.TextMessage, response.message).text)
extension = url.suffix
guess_type_result, _ = guess_type(f"a{extension}")
if guess_type_result:
mimetype = guess_type_result
except Exception:
pass
if not mimetype:
mimetype = "image/jpeg"

View File

@@ -1,3 +1,4 @@
import contextlib
from copy import deepcopy
from typing import Any
@@ -137,11 +138,9 @@ class ToolParameterConfigurationManager:
and parameter.type == ToolParameter.ToolParameterType.SECRET_INPUT
):
if parameter.name in parameters:
try:
has_secret_input = True
has_secret_input = True
with contextlib.suppress(Exception):
parameters[parameter.name] = encrypter.decrypt_token(self.tenant_id, parameters[parameter.name])
except Exception:
pass
if has_secret_input:
cache.set(parameters)

View File

@@ -1,3 +1,4 @@
import contextlib
from copy import deepcopy
from typing import Any, Optional, Protocol
@@ -111,14 +112,12 @@ class ProviderConfigEncrypter:
for field_name, field in fields.items():
if field.type == BasicProviderConfig.Type.SECRET_INPUT:
if field_name in data:
try:
with contextlib.suppress(Exception):
# if the value is None or empty string, skip decrypt
if not data[field_name]:
continue
data[field_name] = encrypter.decrypt_token(self.tenant_id, data[field_name])
except Exception:
pass
self.provider_config_cache.set(data)
return data