Skip to content

fix: replace bare except clauses with except Exception#33426

Open
mango766 wants to merge 1 commit intolanggenius:mainfrom
mango766:fix/replace-bare-except-clauses
Open

fix: replace bare except clauses with except Exception#33426
mango766 wants to merge 1 commit intolanggenius:mainfrom
mango766:fix/replace-bare-except-clauses

Conversation

@mango766
Copy link

Replaces bare except: clauses with except Exception: across multiple files in the API layer.

Bare except: catches SystemExit, KeyboardInterrupt, and GeneratorExit in addition to regular exceptions, which can prevent graceful process shutdown and mask configuration errors.

This is a mechanical change — the exception handling logic remains the same, only the catch scope is narrowed to exclude base exceptions.

Closes #33425

Bare `except:` catches all BaseException subclasses including
SystemExit, KeyboardInterrupt, and GeneratorExit, which can prevent
graceful process shutdown and mask configuration errors. Replace all
bare except clauses in production code with `except Exception:` to
narrow the catch scope while preserving existing behavior.

Co-Authored-By: Claude (claude-opus-4-6) <noreply@anthropic.com>
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors exception handling by replacing bare except clauses with except Exception across various files in the API layer. This is a mechanical change that improves the robustness of the application by ensuring that only application-level exceptions are caught, preventing the accidental suppression of critical system signals without altering the core logic.

Highlights

  • Refactored Exception Handling: Replaced bare except: clauses with except Exception: across multiple files in the API layer to narrow the scope of caught exceptions.
  • Improved Robustness: This change prevents unintended catching of system-level exceptions like SystemExit or KeyboardInterrupt, enhancing application stability by allowing critical system signals to propagate correctly.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • api/commands/account.py
    • Updated exception handling for password and email validation functions.
  • api/core/agent/output_parser/cot_output_parser.py
    • Modified exception handling within the extra_json_from_code_block function for JSON parsing.
  • api/core/rag/datasource/vdb/analyticdb/analyticdb_vector_openapi.py
    • Adjusted exception handling for module imports in the AnalyticdbVectorOpenAPI constructor.
  • api/core/rag/datasource/vdb/lindorm/lindorm_vector.py
    • Updated exception handling in the text_exists method.
  • api/core/rag/datasource/vdb/opensearch/opensearch_vector.py
    • Modified exception handling in the text_exists method.
  • api/extensions/storage/aws_s3_storage.py
    • Refined exception handling in the exists method for S3 object checks.
  • api/extensions/storage/oracle_oci_storage.py
    • Refined exception handling in the exists method for OCI object checks.
  • api/libs/token.py
    • Updated exception handling in the token verification logic within the _verify_token decorator.
  • api/services/app_service.py
    • Modified exception handling for retrieving tool icons in the get_app_meta method.
  • api/services/trigger/webhook_service.py
    • Adjusted exception handling in the generate_webhook_response method.
Activity
  • No specific activity has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request correctly replaces bare except: clauses with except Exception:, which is a good improvement as it prevents catching system-exiting exceptions. I've provided several suggestions to further improve the exception handling by catching more specific exceptions where possible. This will make the code more robust, easier to debug, and clearer in its intent.

try:
valid_password(new_password)
except:
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While except Exception: is better than a bare except:, we can be more specific here. The valid_password function raises a ValueError on failure. Catching ValueError specifically makes the code clearer and safer.

Suggested change
except Exception:
except ValueError:

try:
email_validate(normalized_new_email)
except:
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to the password validation, email_validate raises a ValueError for invalid emails. It's better to catch this specific exception.

Suggested change
except Exception:
except ValueError:

json_blocks.append(json.loads(json_text, strict=False))
return json_blocks
except:
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The primary exception expected in this try block is from json.loads(). It's good practice to catch the specific json.JSONDecodeError rather than a broad Exception. This makes the code's intent clearer.

Suggested change
except Exception:
except json.JSONDecodeError:

from alibabacloud_gpdb20160503.client import Client # type: ignore
from alibabacloud_tea_openapi import models as open_api_models # type: ignore
except:
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This try...except block is intended to handle missing optional dependencies. The specific exception raised in this case is ImportError. It's better to catch ImportError explicitly.

Suggested change
except Exception:
except ImportError:

self._client.get(index=self._collection_name, id=id, params=params)
return True
except:
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The text_exists method returns False if the document is not found. The self._client.get() call will raise a NotFoundError in this case. Catching this specific exception is more precise than catching a general Exception, as it avoids masking other potential issues like connection errors. You'll also need to add from opensearchpy.exceptions import NotFoundError.

Suggested change
except Exception:
except NotFoundError:

self._client.get(index=self._collection_name.lower(), id=id)
return True
except:
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to the Lindorm vector store, self._client.get() will raise NotFoundError if the document doesn't exist. Catching this specific exception is better than a broad Exception as it makes the code's behavior more predictable and avoids hiding other errors like network issues. Remember to import NotFoundError from opensearchpy.exceptions.

Suggested change
except Exception:
except NotFoundError:

Comment on lines +83 to 84
except Exception:
return False
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The head_object call raises a ClientError when an object is not found (404). Catching a generic Exception can mask other important errors, such as invalid credentials or network issues. It's better to specifically catch ClientError and check for the '404' error code. This makes the exists method more robust. You'll need to import ClientError from botocore.exceptions.

Suggested change
except Exception:
return False
except ClientError as e:
if e.response['Error']['Code'] == '404':
return False
else:
# Reraise other client errors
raise

Comment on lines +55 to 56
except Exception:
return False
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This client behaves similarly to the AWS S3 client. The head_object call will raise a ClientError for a missing object. To make this method more robust and avoid hiding other potential errors (like configuration or permission issues), it's better to specifically catch ClientError and check for the '404' error code. Remember to import ClientError from botocore.exceptions.

Suggested change
except Exception:
return False
except ClientError as e:
if e.response['Error']['Code'] == '404':
return False
else:
# Reraise other client errors
raise

raise ValueError(f"provider not found for tool {tool_name}")
meta["tool_icons"][tool_name] = json.loads(provider.icon)
except:
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This try block can raise a ValueError (if the provider is not found) or a json.JSONDecodeError (if the icon data is invalid). It's better to catch these specific exceptions rather than a broad Exception. This makes the code's intent clearer and prevents accidentally catching unrelated errors.

Suggested change
except Exception:
except (ValueError, json.JSONDecodeError):

@dosubot dosubot bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Mar 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bare except: clauses catch SystemExit and KeyboardInterrupt

1 participant