I am using Freemarker template with Spring MVC. Is there a way to return HTTP Status 500 if there is any error rendering the template?
Currently I am using attempt block to handle error, but would like to throw Internal Server error and allow web server to redirect to a default error page
<#attempt>
attempt block
<#recover>
recover block
</#attempt>
Below is my servlet-context.xml
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<beans:property name="cache" value="true" />
<beans:property name="prefix" value="" />
<beans:property name="contentType" value="text/html; charset=UTF-8" />
<beans:property name="suffix" value=".ftl" />
<beans:property name="exposeSessionAttributes" value="true" />
</beans:bean>
Below change in servlet-context.xml resolved the issue. Now it throws HTTP 500 error which is intercepted by web server and I am able to mast the message by redirecting to pre-defined error page.
<beans:bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<beans:property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<beans:property name="freemarkerSettings">
<beans:props>
<beans:prop key="template_exception_handler">rethrow</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
This is the java-based equivalent configuration:
@Bean
public FreeMarkerConfigurer freemarkerConfig() throws TemplateException {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
Properties settings = new Properties();
settings.setProperty(freemarker.template.Configuration.TEMPLATE_EXCEPTION_HANDLER_KEY, "rethrow");
freeMarkerConfigurer.setFreemarkerSettings(settings);
return freeMarkerConfigurer;
}
A simple way to change the mode from "debug" to "rethrow" is to configure it in your application.properties:
spring.freemarker.settings.template_exception_handler=rethrow
来源:https://stackoverflow.com/questions/30426788/freemarker-template-error-handling-with-spring-mvc