refacored error handling