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: try:
sig = inspect.signature(obj) sig = inspect.signature(obj)
return f"{name}{sig}" return f"{name}{sig}"
except: except Exception:
return f"{name}(...)" return f"{name}(...)"
def document_function(name, func, indent=0): 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""" """Clean up temporary file"""
try: try:
os.unlink(file_path) os.unlink(file_path)
except: except Exception:
pass pass
# End-to-end Pipeline Tests # End-to-end Pipeline Tests

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -149,7 +149,7 @@ class BulkClient:
finally: finally:
try: try:
loop.run_until_complete(async_gen.aclose()) loop.run_until_complete(async_gen.aclose())
except: except Exception:
pass pass
async def _export_triples_async(self, flow: str) -> Iterator[Triple]: async def _export_triples_async(self, flow: str) -> Iterator[Triple]:
@ -251,7 +251,7 @@ class BulkClient:
finally: finally:
try: try:
loop.run_until_complete(async_gen.aclose()) loop.run_until_complete(async_gen.aclose())
except: except Exception:
pass pass
async def _export_graph_embeddings_async(self, flow: str) -> Iterator[Dict[str, Any]]: async def _export_graph_embeddings_async(self, flow: str) -> Iterator[Dict[str, Any]]:
@ -349,7 +349,7 @@ class BulkClient:
finally: finally:
try: try:
loop.run_until_complete(async_gen.aclose()) loop.run_until_complete(async_gen.aclose())
except: except Exception:
pass pass
async def _export_document_embeddings_async(self, flow: str) -> Iterator[Dict[str, Any]]: async def _export_document_embeddings_async(self, flow: str) -> Iterator[Dict[str, Any]]:
@ -448,7 +448,7 @@ class BulkClient:
finally: finally:
try: try:
loop.run_until_complete(async_gen.aclose()) loop.run_until_complete(async_gen.aclose())
except: except Exception:
pass pass
async def _export_entity_contexts_async(self, flow: str) -> Iterator[Dict[str, Any]]: 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"] for v in object["values"]
] ]
except: except Exception:
raise ProtocolException(f"Response not formatted correctly") raise ProtocolException(f"Response not formatted correctly")
def all(self): def all(self):
@ -288,6 +288,6 @@ class Config:
try: try:
return object["config"], object["version"] return object["config"], object["version"]
except: except Exception:
raise ProtocolException(f"Response not formatted correctly") raise ProtocolException(f"Response not formatted correctly")

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -50,7 +50,7 @@ def format_parameters(params_metadata, config_api):
if default is not None: if default is not None:
type_info = f"{param_type} (default: {default})" type_info = f"{param_type} (default: {default})"
except: except Exception:
# If we can't get type definition, just show the type name # If we can't get type definition, just show the type name
pass 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 type_def_value = config_api.get([key])[0].value
param_type_def = json.loads(type_def_value) param_type_def = json.loads(type_def_value)
display_value = get_enum_description(value, param_type_def) 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 # If we can't get the type definition, just use the original value
display_value = value display_value = value

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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