What are different ways to handle error in FreeMarker template?

纵饮孤独 提交于 2020-01-10 14:10:50

问题


How to suppress FreeMarker template error? I am looking here: http://freemarker.sourceforge.net/docs/pgui_config_errorhandling.html But I do not understand how to "TemplateExceptionHandler.IGNORE_HANDLER." I am using Struts2 and also how to show another ftl page instead of showing the stack trace?

class MyTemplateExceptionHandler implements TemplateExceptionHandler {
    public void handleTemplateException(TemplateException te, Environment env, java.io.Writer out)
            throws TemplateException {
        try {
            out.write("[ERROR: " + te.getMessage() + "]");
        } catch (IOException e) {
            throw new TemplateException("Failed to print error message. Cause: " + e, env);
        }
    }
}

...

cfg.setTemplateExceptionHandler(new MyTemplateExceptionHandler());

Found the above piece at http://freemarker.sourceforge.net/docs/pgui_config_errorhandling.html How do I use this? That last line, where does cfg come from?

"Main entry point into the FreeMarker API"... http://massapi.com/source/freemarker-2.3.18/src/freemarker/template/Configuration.java.html

So, that is the main entry point, I am guessing cfg comes from this class. I am still not seeing how the controller will come into my class MyTemplateExceptionHandler.

Where will the following line needs to go?

cfg.setTemplateExceptionHandler(new MyTemplateExceptionHandler());

And is it just a matter of placing this line in correct spot?

This is how my current class looks like:

    import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Properties;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.WebappTemplateLoader;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.jsp.TaglibFactory;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.ext.servlet.HttpRequestParametersHashModel;
import freemarker.ext.servlet.HttpSessionHashModel;
import freemarker.ext.servlet.ServletContextHashModel;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateModel;

import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.views.JspSupportServlet;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.apache.struts2.views.freemarker.ScopesHashModel;
import org.apache.struts2.views.freemarker.StrutsBeanWrapper;
import org.apache.struts2.views.freemarker.StrutsClassTemplateLoader;
import org.omg.CORBA.PUBLIC_MEMBER;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.FileManager;
import com.opensymphony.xwork2.util.ValueStack;

public class MyTemplateExceptionHandler extends org.apache.struts2.views.freemarker.FreemarkerManager {

    freemarker.template.Configuration configuration = new freemarker.template.Configuration();

    public MyTemplateExceptionHandler() {
        System.out.println("MyTemplateExceptionHandler constructor()");
        configuration.setTemplateExceptionHandler(new Test1());
    }

    class Test1 implements TemplateExceptionHandler {

        @Override
        public void handleTemplateException(TemplateException te, Environment env, java.io.Writer out) throws TemplateException {
            System.out.println("MyTemplateExceptionHandler1 handleTemplateException()");
            try {
                out.write("[ERROR TEST TEST: " + te.getMessage() + "]");
            } catch (IOException e) {
                throw new TemplateException("Failed to print error message. Cause: " + e, env);
            }
        }
    }
}

My code is going into MyTemplateExceptionHandler constructor(). But not into MyTemplateExceptionHandler1 handleTemplateException(). What do I need to do?

I am still seeing the yellow FTL stack trace.

Same thing is being pointed out on this blog: http://blog.cherouvim.com/freemarker-exception-handling/ Where excatly do I configure my freemarker and how? I am still stuck as to where that line needs to go.

My other question is, the class posted on the blog seems to be an inner class, do I just put that inner class into any class or is that an outer class?


回答1:


If you want to set TemplateExceptionHandler to TemplateExceptionHandler.IGNORE_HANDLER in Struts2 you need to extend org.apache.struts2.views.freemarker.FreemarkerManager class, override init and createConfiguration methods and configure your custom manager in struts.properties file.

struts.freemarker.manager.classname = your.package.YourFreeMarkerManager  

UPDATE

Your custom FreemarkerManager should look like that:

public class MyFreemarkerManager extends
    org.apache.struts2.views.freemarker.FreemarkerManager {

private static final Logger LOG = LoggerFactory
        .getLogger(MyFreemarkerManager.class);

@Override
public void init(ServletContext servletContext) throws TemplateException {
    config = createConfiguration(servletContext);

    // Set defaults:
    config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
    contentType = DEFAULT_CONTENT_TYPE;

    // Process object_wrapper init-param out of order:
    wrapper = createObjectWrapper(servletContext);
    if(LOG.isDebugEnabled()) {
        LOG.debug("Using object wrapper of class " + wrapper.getClass().getName());
    }
    config.setObjectWrapper(wrapper);

    // Process TemplatePath init-param out of order:
    templatePath = servletContext.getInitParameter(INITPARAM_TEMPLATE_PATH);
    if(templatePath == null) {
        templatePath = servletContext.getInitParameter("templatePath");
    }

    config
            .setTemplateLoader(createTemplateLoader(servletContext, templatePath));

    loadSettings(servletContext);
}

@Override
protected Configuration createConfiguration(ServletContext servletContext)
        throws TemplateException {
    Configuration configuration = new Configuration();

    configuration
            .setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

    if(mruMaxStrongSize > 0) {
        configuration.setSetting(Configuration.CACHE_STORAGE_KEY, "strong:"
                + mruMaxStrongSize);
    }
    if(templateUpdateDelay != null) {
        configuration.setSetting(Configuration.TEMPLATE_UPDATE_DELAY_KEY,
                templateUpdateDelay);
    }
    if(encoding != null) {
        configuration.setDefaultEncoding(encoding);
    }

    configuration.setWhitespaceStripping(true);

    return configuration;
}
}

Put that constant in your struts.xml file:

<constant name="struts.freemarker.manager.classname" value="your_package.MyFreemarkerManager" /> 



回答2:


If you want to handle it inside freemarker, use its attempt-recover mechanism:

<#attempt>
  attempt block
<#recover>
  recover block
</#attempt>

It's analogous to Java's try-catch.




回答3:


You can also use the freemarker.properties with the following key=value:

template_exception_handler = rethrow

Just put your freemarker.properties in the classpath.

I think this is a lot cleaner approach.



来源:https://stackoverflow.com/questions/15123743/what-are-different-ways-to-handle-error-in-freemarker-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!