added error handling function and refactored public API
added comment to handleError