Error handling for query()