如何在SQLAlchemy中提取孤立的SQL语法错误信息?
Absolutely, you can pull out that core error message cleanly! The key here is that SQLAlchemy's ProgrammingError wraps the underlying database driver's exception (in your case, psycopg2's error). You can access that original error directly via the orig attribute to get the precise message you need.
Here's how to adjust your code to extract the core error:
from sqlalchemy import text from sqlalchemy.exc import ProgrammingError try: [row for row in db.execute(text("select * from userds"), **args)] except ProgrammingError as error: # Get the original psycopg2 error object original_db_error = error.orig # The `pgerror` attribute holds the detailed error message from PostgreSQL # Split on newline to grab just the first line (the core error) core_error_message = original_db_error.pgerror.split('\n')[0].strip() print(core_error_message) # Will output: relation "userds" does not exist
This approach is more reliable than parsing the full string from SQLAlchemy's error because it uses the structured error information provided by the database driver. For psycopg2 specifically, the pgerror field includes the exact error details PostgreSQL returns, and the first line is almost always the concise, core error you're after.
If you want to handle edge cases (like multi-line error messages where the core message isn't the first line), you could add some additional parsing logic, but for most common SQL syntax or relation errors, splitting the first line works perfectly.
内容的提问来源于stack exchange,提问作者seanbehan

