问题
I am writing a Java Utility to generate output files using freemarker template. I have a List of objects that I write into a file using freemarker. E.g. My java object is an employee having fName, lName and age. I am using following code snippet to generate the output file:
<#list employees as e>
Fname: ${e.fName} Lname: ${e.lName} Age: ${e.age}
</#list>
Now, I am using a custom template exception handler that handle exceptions in case fName, lName OR age is missing from the employee object.
configuration.setTemplateExceptionHandler(new FreemarkerExceptionHandler());
I want to read the employee object that is throwing the exception in the FreemarkerExceptionHandler class, but am unable to read it. I am using the following code to read the list of employees, but am getting all the employees, rather than one specific employee that lead to this error.
TemplateHashModel templateHashModel = environment.getDataModel();
TemplateModel templateModel = templateHashModel.get("employees");
List<Employee> emps = simpleSequence.toList();
Can anyone please confirm if this is feasible in freemarker to catch the object that lead to exception.
回答1:
There's no simple way to do that as far as I see. My idea is extending DefaultObjectWrapper (assuming you are using that - see Configuration.getObjectWrapper), so when the subvariable (like fNameo) is get via TemplateHashModel.get(String), you can catch any exceptions throw by super.get(String) in your override of TemplateHashModel.get, and then throw your own TemplateException subclass instance, into which you put the parent object in a field you have added for that. (And also you probably want to add the original exception as the cause exception of your exception.)
来源:https://stackoverflow.com/questions/57789211/read-java-object-that-leads-to-templateexception-in-freemarker-template-engine