Spring + Thymeleaf引擎错误处理和记录

时间:2019-03-01 15:00:26

标签: spring spring-boot thymeleaf splunk custom-error-handling

我们公司正在将模板引擎从Velocity切换到Thymeleaf。我们使用Splunk进行日志记录,并使用Velocity能够实现org.apache.velocity.runtime.log.LogChute来处理自定义日志记录(格式并记录到我们的splunk日志),但是我找不到Thymeleaf的任何类似类。 >

到目前为止,我已经尝试了几种方法。首先,我尝试扩展实际的Thymeleaf引擎,并在process方法周围添加try / catch包装器,但是不幸的是,该方法是最终方法。我看到了一个建议,添加一个过滤器来捕获百里香的错误,但是一定有一部分吞没了该错误,因为它永远不会到达那个catch块。

这时我唯一想到的选择是将org.thymeleaf.TemplateEngine日志简单地拖入我们的splunk日志中,但是这样就不能正确格式化以进行提取,并且我不能添加任何自定义字段。 / p>

有人有什么主意吗?

编辑:

哇,所以我只是重试了Filter方法,但是它起作用了,但是捕获的异常是org.springframework.web.util.NestedServletException,所以JRebel一定不会重新加载我的更改来捕获Exception而不是TemplateEngineException我最后尝试过。

也就是说,如果有人有更好的方法,我很想听听。 我是整个问题发布的新手;我应该发布答案吗?

1 个答案:

答案 0 :(得分:0)

过滤器方法最终奏效了,但是TemplateEngineExceptionNestedServletException包裹着。

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.web.util.NestedServletException;
import org.thymeleaf.exceptions.TemplateEngineException;

/**
 * Filter to catch Thymeleaf template errors
 */
public class ThymeleafErrorFilter implements Filter {

    @Override
    public void init(final FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (final NestedServletException nse) {
            if(nse.getCause() instanceof TemplateEngineException) {
                //Do stuff here
                ...
            }

            throw nse;
        }
    }

    @Override
    public void destroy() {
    }
}

然后注册过滤器

    /**
     * @return thymeleaf error filter
     */
    @Bean
    public FilterRegistrationBean thymeleafErrorFilter() {
        FilterRegistrationBean thymeleafErrorFilter = new FilterRegistrationBean();
        thymeleafErrorFilter.setName("thymeleafErrorFilter");
        thymeleafErrorFilter.setFilter(new ThymeleafErrorFilter());
        thymeleafErrorFilter.addUrlPatterns("/*");
        return thymeleafErrorFilter;
    }