Restructured and added support to throw error if result is empty