better error handling and query generation