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

问题描述 投票:1回答:1

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

到目前为止,我尝试了几种方法。首先,我尝试扩展实际的Thymeleaf引擎并在process方法周围添加try / catch包装器,但不幸的是,这种方法是最终的。我看到了一个建议,要添加一个过滤器来捕捉百万美元的错误,但必须要吞下错误,因为它永远不会到达那个捕获块。

我现在能想到的唯一选择是简单地将org.thymeleaf.TemplateEngine日志拖入我们的splunk日志中,但是它将无法正确格式化以供摄取,我无法添加任何自定义字段。

有人有什么想法吗?

编辑:

哇,所以我只是重试了Filter方法并且它有效,但是被捕获的异常是org.springframework.web.util.NestedServletException,所以当我最后一次尝试时,JRebel一定不能重新加载我的更改以捕获Exception而不是TemplateEngineException

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

spring spring-boot thymeleaf splunk custom-error-handling
1个回答
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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.