add error handling and fix a bug