Optimizing error handling for database queries