refactoring:  wrapping code generation into tryCatch to handle encoding errors