Added Error handling in factory function