如何管理Spring中过滤器中抛出的异常? [英] How to manage exceptions thrown in filters in Spring?

查看:606
本文介绍了如何管理Spring中过滤器中抛出的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用通用方法来管理5xx错误代码,让我们特别说明db在整个spring应用程序中出现故障的情况。我想要一个漂亮的错误json而不是堆栈跟踪。

I want to use generic way to manage 5xx error codes, let's say specifically the case when the db is down across my whole spring application. I want a pretty error json instead of a stack trace.

对于控制器,我有一个 @ControllerAdvice 类用于不同的异常,这也是一个案例,即db正在请求中间停止。但这并不是全部。我也碰巧有一个自定义 CorsFilter 扩展 OncePerRequestFilter 当我打电话给 doFilter 我得到 CannotGetJdbcConnectionException ,它不会由 @ControllerAdvice 管理。我在线阅读了几件让我更加困惑的事情。

For the controllers I have a @ControllerAdvice class for the different exceptions and this is also catching the case that the db is stopping in the middle of the request. But this is not all. I also happen to have a custom CorsFilter extending OncePerRequestFilter and there when i call doFilter i get the CannotGetJdbcConnectionException and it will not be managed by the @ControllerAdvice. I read several things online that only made me more confused.

所以我有很多问题:


  • 我是否需要实施自定义过滤器?我找到了 ExceptionTranslationFilter 但这只处理 AuthenticationException AccessDeniedException

  • 我想实现自己的 HandlerExceptionResolver ,但这让我怀疑,我没有任何自定义异常来管理,那里必须是比这更明显的方式。我还尝试添加一个try / catch并调用 HandlerExceptionResolver 的实现(应该足够好了,我的异常没什么特别的)但是这不会在响应中返回任何内容,我得到一个状态200和一个空体。

  • Do i need to implement a custom filter? I found the ExceptionTranslationFilter but this only handles AuthenticationException or AccessDeniedException.
  • I thought of implementing my own HandlerExceptionResolver, but this made me doubt, I don't have any custom exception to manage, there must be a more obvious way than this. I also tried to add a try/catch and call an implementation of the HandlerExceptionResolver (should be good enough, my exception is nothing special) but this is not returning anything in the response, i get a status 200 and an empty body.

有什么好方法可以解决这个问题吗?谢谢

Is there any good way to deal with this? Thanks

推荐答案

所以这就是我所做的:

我读过有关过滤器此处的基础知识,我发现我需要创建一个自定义过滤器首先在过滤器链中,将有一个try catch来捕获可能在那里发生的所有运行时异常。然后我需要手动创建json并将其放入响应中。

I read the basics about filters here and I figured out that I need to create a custom filter that will be first in the filter chain and will have a try catch to catch all runtime exceptions that might occur there. Then i need to create the json manually and put it in the response.

所以这是我的自定义过滤器:

So here is my custom filter:

public class ExceptionHandlerFilter extends OncePerRequestFilter {

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (RuntimeException e) {

            // custom error response class used across my project
            ErrorResponse errorResponse = new ErrorResponse(e);

            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.getWriter().write(convertObjectToJson(errorResponse));
    }
}

    public String convertObjectToJson(Object object) throws JsonProcessingException {
        if (object == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }
}

然后我在web.xml中添加它 CorsFilter 。它的工作原理!

And then i added it in the web.xml before the CorsFilter. And it works!

<filter> 
    <filter-name>exceptionHandlerFilter</filter-name> 
    <filter-class>xx.xxxxxx.xxxxx.api.controllers.filters.ExceptionHandlerFilter</filter-class> 
</filter> 


<filter-mapping> 
    <filter-name>exceptionHandlerFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

<filter> 
    <filter-name>CorsFilter</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter> 

<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

这篇关于如何管理Spring中过滤器中抛出的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆