Ordinary
About

Spring Filter 내부 Exception

profileordilov / 2022. 3. 7

@RestControllerAdvice로 에러를 전역처리하는데 filter 내부에서 에러는 처리되지 않았습니다. 이 경우 처리를 위해서 겪을 수 있는 문제점들이 있습니다.

AuthenticationEntryPoint

인증되지 않은 에러인 401 에러인 경우 필터를 거치고 AuthenticationEntryPoint 구현체에서 에러가 처리됩니다. 이 인터페이스를 구현하고 commence 메서드를 오버라이드하면 커스텀 처리가 가능해집니다.

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException { log.error("잘못된 인증 요청이 들어왔습니다. Message - {}", e.getMessage()); ErrorCode errorCode = (ErrorCode) request.getAttribute("errorCode"); if (errorCode == null) { errorCode = ErrorCode.UNAUTHORIZED; } ObjectMapper mapper = new ObjectMapper(); String error = mapper.writeValueAsString(CommonResponse.fail(errorCode)); response.setCharacterEncoding("UTF-8"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write(error); } }

Filter 중간에서 처리

Fitler 중간에서 메서드 파리미터로 넘어온 HttpServletResponse를 이용해 중간에 응답을 보낼 수 있습니다. 방법으로는 sendError 메서드를 이용하거나 response에 write 하는 방식으로 중간에 응답을 보내면 됩니다. 하지만 중간에서 처리하는 경우 응답 보낸 response를 다음 filter로 보내면 안됩니다. 응답이 이미 처리된 형태이기 때문에 다음 필터로 넘어가면 에러가 발생합니다.

response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); ... filterChain.doFilter(request, response); // 에러