Improve error handling and add basic type checking