spring filter exception handling

Solutions on MaxInterview for spring filter exception handling by the best coders in the world

showing results for - "spring filter exception handling"
Elisa
01 Mar 2019
1public class ExceptionHandlerFilter extends OncePerRequestFilter {
2
3    @Override
4    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
5        try {
6            filterChain.doFilter(request, response);
7        } catch (RuntimeException e) {
8
9            // custom error response class used across my project
10            ErrorResponse errorResponse = new ErrorResponse(e);
11
12            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
13            response.getWriter().write(convertObjectToJson(errorResponse));
14    }
15}
16
17    public String convertObjectToJson(Object object) throws JsonProcessingException {
18        if (object == null) {
19            return null;
20        }
21        ObjectMapper mapper = new ObjectMapper();
22        return mapper.writeValueAsString(object);
23    }
24}