refactoring js and error handling