240223 TIL #329 필터 예외 핸들링

김춘복·2024년 2월 22일
0

TIL : Today I Learned

목록 보기
329/494

Today I Learned

예외 처리 중 필터에서 발생한 예외를 핸들링하는 방법에 대해 정리해보았다.


필터에서 발생한 예외 핸들링 방법

Filter Exception Handling. 참고사이트

필터의 예외는 @ControllerAdvice로 처리하지 못한다.
그래서 예외처리를 위한 새로운 filter를 만들어 처리하고자하는 filter의 앞에다 두면 된다.
(.addFilterBefore(new ExceptionHandlerFilter(), JwtAuthFilter.class);)

@Slf4j
public class ExceptionHandlerFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request,response);
        }catch(UsernameNotFoundException e) {
            jwtExceptionHandler(response,e.getMessage(), HttpStatus.BAD_REQUEST);
        }catch (RuntimeException e){
            jwtExceptionHandler(response,e.getMessage().split(":")[0], HttpStatus.BAD_REQUEST);
        }catch (Exception e){
            jwtExceptionHandler(response,e.getMessage().split(":")[0], HttpStatus.BAD_REQUEST);
        }
    }

    public void jwtExceptionHandler(HttpServletResponse response, String msg, HttpStatus httpStatus) {
        response.setStatus(httpStatus.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");
        try {
            String json = new ObjectMapper().writeValueAsString(new MessageResponseDto(msg,httpStatus));
            response.getWriter().write(json);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
profile
꾸준히 성장하기 위해 매일 log를 남깁니다!

0개의 댓글