exception handling for filter in spring

后端 未结 7 876
既然无缘
既然无缘 2020-12-17 14:59

I am handling exceptions in spring using @ExceptionHandler. Any exception thrown by controller is caught using method annotated with @ExceptionHandler and action is taken ac

7条回答
  •  一生所求
    2020-12-17 16:04

    I built my application with rest api, so I resolved this problem by catching it in the filter that may throw an exception and then writing something back. Remember that filterChain.doFilter(request, response); must be included.

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            // something may throw an exception
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            // ResponseWrapper is a customized class
            ResponseWrapper responseWrapper = new ResponseWrapper().fail().msg(e.getMessage());
            response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(JSON.toJSONString(responseWrapper));
        }
    }
    

提交回复
热议问题