在 python3 中出现 psycopg2 错误

get psycopg2 errors in python3

我有 psycopg2 版本 2.6.1 我想获取一些错误,但它没有按预期工作:

try:
    pgconn = psycopg2.connect(database="foobar", host="dbtest.example.de", user="postgresss")
except psycopg2.OperationalError:
    print(psycopg2.OperationalError.pgerror)
   .....:     
<member 'pgerror' of 'psycopg2.Error' objects>

或:

try:                       
    pgconn = psycopg2.connect(database="foobar", host="dbtest.example.de", user="postgresss")
except psycopg2.OperationalError:
    print(psycopg2.OperationalError.diag)
   .....:     
<attribute 'diag' of 'psycopg2.Error' objects>

我怎样才能看到像 "no pg_hba.conf entry for host xyz"

这样的正确消息

您需要引用异常实例:

try:
    pgconn = psycopg2.connect(database="foobar", host="dbtest.example.de", user="postgresss")
except psycopg2.OperationalError as e:
    print(e)