amazon-web-servicesboto3aws-rds-data-service

Catching and Parsing AWS RDSDataService exceptions


I am using RDSDataService in a lambda to execute queries in an Aurora Serverless DB. It's all good when everything runs fine, but when there is an error running the query I get something like this

An error occurred (BadRequestException) when calling the ExecuteStatement operation: ERROR: duplicate key value violates unique constraint "user_role_role_name_key" Detail: Key (role_name)=(Test3 ) already exists.

I am catching that using a generic except Exception as e and then printing e.

Questions:

  1. What package do I need to import to catch BadRequestException
  2. How would I parse it to extract the detail part?

Solution

  • AWS confirmed that it is not possible to properly parse the details of a Data API exception when using Postgresql (see this github issue for updates).

    If using the MySQL version of Aurora, the aurora-data-api package effectively returns a better exception format, since the SQLSTATE code can be parsed. We can see in this internal function the difference in parsing.


    For now, the only way to parse the exceptions from a Postgresql Aurora DB with Data API is to use string comparison like this:

    if errorMessage.contains('a known substring of a specific exception message'):
       # Here we "know" the exception type