fix: replace 53 bare excepts with except Exception

This commit is contained in:
haosenwang1018 2026-02-25 07:35:07 +00:00
parent 3666ece2c5
commit 9c23492286
34 changed files with 53 additions and 53 deletions

View file

@ -109,7 +109,7 @@ def format_signature(name, obj):
try:
sig = inspect.signature(obj)
return f"{name}{sig}"
except:
except Exception:
return f"{name}(...)"
def document_function(name, func, indent=0):

View file

@ -134,7 +134,7 @@ Charlie Davis,charlie@email.com,39,DE,inactive"""
"""Clean up temporary file"""
try:
os.unlink(file_path)
except:
except Exception:
pass
# End-to-end Pipeline Tests

View file

@ -63,7 +63,7 @@ Charlie Davis,charlie@email.com,39,DE"""
"""Clean up temporary file"""
try:
os.unlink(file_path)
except:
except Exception:
pass
@pytest.mark.asyncio

View file

@ -103,7 +103,7 @@ def mock_calculator_tool():
result *= int(p.strip())
return str(result)
return str(eval(expression)) # Simplified for testing
except:
except Exception:
return "Error: Invalid expression"
return calculator_tool

View file

@ -130,7 +130,7 @@ Answer: The capital of France is Paris."""
parts = expression.split('+')
return str(sum(int(p.strip()) for p in parts))
return str(eval(expression))
except:
except Exception:
return "Error: Invalid expression"
tools = {
@ -676,7 +676,7 @@ Answer: The capital of France is Paris."""
import json
try:
args = json.loads(args_text)
except:
except Exception:
args = {"raw": args_text}
return {

View file

@ -57,7 +57,7 @@ class TestErrorHandlingEdgeCases:
"""Clean up temporary file"""
try:
os.unlink(file_path)
except:
except Exception:
pass
# File Access Error Tests

View file

@ -147,7 +147,7 @@ Bob Johnson,bob@company.org,42,UK"""
"""Clean up temporary file"""
try:
os.unlink(file_path)
except:
except Exception:
pass
# Schema Suggestion Tests

View file

@ -136,7 +136,7 @@ Bob Johnson,bob@company.org,42,UK,2024-01-10,inactive"""
"""Clean up temporary file"""
try:
os.unlink(file_path)
except:
except Exception:
pass
# Schema Suggestion Tests

View file

@ -27,7 +27,7 @@ class TestXMLXPathParsing:
"""Clean up temporary file"""
try:
os.unlink(file_path)
except:
except Exception:
pass
def parse_xml_with_cli(self, xml_data, format_info, sample_size=100):
@ -139,7 +139,7 @@ class TestXMLXPathParsing:
"""Clean up temporary file"""
try:
os.unlink(file_path)
except:
except Exception:
pass
# UN Data Format Tests (CLI-level testing)

View file

@ -25,7 +25,7 @@ def check_error(response):
try:
msg = response["error"]["message"]
tp = response["error"]["type"]
except:
except Exception:
raise ApplicationException(response["error"])
raise ApplicationException(f"{tp}: {msg}")
@ -201,7 +201,7 @@ class Api:
try:
# Parse the response as JSON
object = resp.json()
except:
except Exception:
raise ProtocolException(f"Expected JSON response")
check_error(object)

View file

@ -22,7 +22,7 @@ def check_error(response):
try:
msg = response["error"]["message"]
tp = response["error"]["type"]
except:
except Exception:
raise ApplicationException(response["error"])
raise ApplicationException(f"{tp}: {msg}")
@ -85,7 +85,7 @@ class AsyncFlow:
try:
obj = await resp.json()
except:
except Exception:
raise ProtocolException(f"Expected JSON response")
check_error(obj)

View file

@ -149,7 +149,7 @@ class BulkClient:
finally:
try:
loop.run_until_complete(async_gen.aclose())
except:
except Exception:
pass
async def _export_triples_async(self, flow: str) -> Iterator[Triple]:
@ -251,7 +251,7 @@ class BulkClient:
finally:
try:
loop.run_until_complete(async_gen.aclose())
except:
except Exception:
pass
async def _export_graph_embeddings_async(self, flow: str) -> Iterator[Dict[str, Any]]:
@ -349,7 +349,7 @@ class BulkClient:
finally:
try:
loop.run_until_complete(async_gen.aclose())
except:
except Exception:
pass
async def _export_document_embeddings_async(self, flow: str) -> Iterator[Dict[str, Any]]:
@ -448,7 +448,7 @@ class BulkClient:
finally:
try:
loop.run_until_complete(async_gen.aclose())
except:
except Exception:
pass
async def _export_entity_contexts_async(self, flow: str) -> Iterator[Dict[str, Any]]:

View file

@ -252,7 +252,7 @@ class Config:
)
for v in object["values"]
]
except:
except Exception:
raise ProtocolException(f"Response not formatted correctly")
def all(self):
@ -288,6 +288,6 @@ class Config:
try:
return object["config"], object["version"]
except:
except Exception:
raise ProtocolException(f"Response not formatted correctly")

View file

@ -134,7 +134,7 @@ class SocketClient:
# Clean up async generator
try:
loop.run_until_complete(async_gen.aclose())
except:
except Exception:
pass
async def _send_request_async(

View file

@ -225,7 +225,7 @@ class Subscriber:
try:
id = msg.properties()["id"]
except:
except Exception:
id = None
value = msg.value()

View file

@ -43,7 +43,7 @@ class Field:
try:
type = FieldType[type.upper()]
except:
except Exception:
raise RuntimeError(f"Field type {type} is not known")
pri = True if pri == "pri" else False

View file

@ -37,7 +37,7 @@ async def load_de(running, queue, url):
if msg is None:
break
except:
except Exception:
# Hopefully it's TimeoutError. Annoying to match since
# it changed in 3.11.
continue
@ -93,7 +93,7 @@ async def loader(running, de_queue, path, format, user, collection):
try:
unpacked = unpacker.unpack()
except:
except Exception:
break
if user:
@ -113,7 +113,7 @@ async def loader(running, de_queue, path, format, user, collection):
# Successful put message, move on
break
except:
except Exception:
# Hopefully it's TimeoutError. Annoying to match since
# it changed in 3.11.
continue
@ -129,7 +129,7 @@ async def loader(running, de_queue, path, format, user, collection):
# Successful put message, move on
break
except:
except Exception:
# Hopefully it's TimeoutError. Annoying to match since
# it changed in 3.11.
continue

View file

@ -30,7 +30,7 @@ session.mount('file://', FileAdapter())
try:
os.mkdir("doc-cache")
except:
except Exception:
pass
documents = [

View file

@ -163,7 +163,7 @@ def load_structured_data(
try:
import os
os.unlink(temp_descriptor.name)
except:
except Exception:
pass
elif discover_schema:

View file

@ -72,7 +72,7 @@ async def put(url, user, id, input, token=None):
try:
unpacked = unpacker.unpack()
except:
except Exception:
break
kind, msg = read_message(unpacked, id, user)

View file

@ -31,7 +31,7 @@ async def fetch_de(running, queue, user, collection, url):
try:
msg = await asyncio.wait_for(ws.receive(), 1)
except:
except Exception:
continue
if msg.type == aiohttp.WSMsgType.TEXT:
@ -94,7 +94,7 @@ async def output(running, queue, path, format):
try:
msg = await asyncio.wait_for(queue.get(), 0.5)
except:
except Exception:
# Hopefully it's TimeoutError. Annoying to match since
# it changed in 3.11.
continue

View file

@ -130,7 +130,7 @@ def main():
if args.schema:
try:
schobj = json.loads(args.schema)
except:
except Exception:
raise RuntimeError("JSON schema must be valid JSON")
else:
schobj = None

View file

@ -50,7 +50,7 @@ def format_parameters(params_metadata, config_api):
if default is not None:
type_info = f"{param_type} (default: {default})"
except:
except Exception:
# If we can't get type definition, just show the type name
pass

View file

@ -109,7 +109,7 @@ def format_parameters(flow_params, blueprint_params_metadata, config_api):
type_def_value = config_api.get([key])[0].value
param_type_def = json.loads(type_def_value)
display_value = get_enum_description(value, param_type_def)
except:
except Exception:
# If we can't get the type definition, just use the original value
display_value = value

View file

@ -36,7 +36,7 @@ def show_config(url, token=None):
fmt(values.get("input_price")),
fmt(values.get("output_price")),
))
except:
except Exception:
costs.append((
model, "-", "-"
))

View file

@ -155,7 +155,7 @@ class OntologySelector:
import json
try:
definition = json.loads(definition.replace("'", '"'))
except:
except Exception:
definition = eval(definition) # Fallback for dict-like strings
# Get the actual ontology and element

View file

@ -18,11 +18,11 @@ try:
except LookupError:
try:
nltk.download('punkt_tab', quiet=True)
except:
except Exception:
# Fallback to older punkt if punkt_tab not available
try:
nltk.download('punkt', quiet=True)
except:
except Exception:
pass
try:
@ -30,11 +30,11 @@ try:
except LookupError:
try:
nltk.download('averaged_perceptron_tagger_eng', quiet=True)
except:
except Exception:
# Fallback to older name
try:
nltk.download('averaged_perceptron_tagger', quiet=True)
except:
except Exception:
pass
try:
@ -62,7 +62,7 @@ class SentenceSplitter:
# Try newer punkt_tab first
self.sent_detector = nltk.data.load('tokenizers/punkt_tab/english/')
logger.info("Using NLTK sentence tokenizer (punkt_tab)")
except:
except Exception:
# Fallback to older punkt
self.sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
logger.info("Using NLTK sentence tokenizer (punkt)")

View file

@ -37,7 +37,7 @@ class ConstantEndpoint:
if tokens[0] != "Bearer":
return web.HTTPUnauthorized()
token = tokens[1]
except:
except Exception:
token = ""
if not self.auth.permitted(token, self.operation):

View file

@ -41,7 +41,7 @@ class MetricsEndpoint:
if tokens[0] != "Bearer":
return web.HTTPUnauthorized()
token = tokens[1]
except:
except Exception:
token = ""
if not self.auth.permitted(token, self.operation):

View file

@ -64,7 +64,7 @@ class SocketEndpoint:
"""Enhanced handler with better cleanup"""
try:
token = request.query['token']
except:
except Exception:
token = ""
if not self.auth.permitted(token, self.operation):

View file

@ -44,7 +44,7 @@ class StreamEndpoint:
if tokens[0] != "Bearer":
return web.HTTPUnauthorized()
token = tokens[1]
except:
except Exception:
token = ""
if not self.auth.permitted(token, self.operation):

View file

@ -36,7 +36,7 @@ class VariableEndpoint:
if tokens[0] != "Bearer":
return web.HTTPUnauthorized()
token = tokens[1]
except:
except Exception:
token = ""
if not self.auth.permitted(token, self.operation):

View file

@ -31,12 +31,12 @@ class PromptManager:
try:
system = json.loads(config["system"])
except:
except Exception:
system = "Be helpful."
try:
ix = json.loads(config["template-index"])
except:
except Exception:
ix = []
prompts = {}
@ -68,7 +68,7 @@ class PromptManager:
try:
self.system_template = ibis.Template(self.config.system_template)
except:
except Exception:
raise RuntimeError("Error in system template")
self.templates = {}
@ -126,7 +126,7 @@ class PromptManager:
try:
obj = self.parse_json(resp)
except:
except Exception:
logger.error(f"JSON parse failed: {resp}")
raise RuntimeError("JSON parse fail")

View file

@ -59,7 +59,7 @@ class WebSocketManager:
for queue in self.pending_requests.values():
try:
await queue.put({"error": str(e)})
except:
except Exception:
pass
self.pending_requests.clear()