How do you get the error message out of a ProgrammingError exception?

Viewed 493

I'm using redshift_connector and I can't figure out how to just extract the error message of a failed query without parsing the exception as a string. I can't find any attributes on the object using dict(), and I'm not sure how the source of the exception is setting things, but I just want the message.

If I print it this way:

print(f"ERROR: {getattr(ex, 'message', repr(ex))}")

It doesn't find the attribute 'message', so defaults to this:

redshift_connector.error.ProgrammingError: {'S': 'ERROR', 'C': 'XX000', 'M': 'Received error 503 from server', 'D': '\n  -----------------------------------------------\n  error:  Received error 503 from server\n  code:      32004\n  context:   \n  query:     657118\n  location:  exfunc_data.cpp:312\n  process:   query0_109_657118 [pid=27456]\n  -----------------------------------------------\n', 'F': '/home/ec2-user/padb/src/sys/xen_execute.cpp', 'L': '9801', 'R': 'pg_throw'}

Initial thought is to make a dict() out of it, but that comes out empty.

I can get at the 'M' (message) if I do something like this:

json.loads(str(ex).replace("'", '"').replace("\n", "\\n"))['M']

..but that is just gross. There has to be a better way to get at this?

Any ideas?

1 Answers

Well, I actually didn't find a straight way but this is "less gross" and also doesn't require any imports (like json).

except redshift_connector.error.ProgrammingError as exception:
        print(dict(exception.args[0]).get('M'))
Related