Refactored error handling and fixed serialization issues