improved query matching and error handling