You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQLAlchemy中提取孤立的SQL语法错误信息?

Extracting Core SQL Syntax Errors from SQLAlchemy ProgrammingError

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:58:00