ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 패스트캠퍼스 챌린지 14일차
    JAVA/Spring 2021. 11. 14. 23:59

    1. 예외처리를 제대로 안했을 때의 문제점

     

    지난 시간에 예외 처리를 했던 방법으로는 각각의 Controller에 Exception 처리를 해주어야하기 때문에 Controller가 많아질 경우 너무 많은 Exception 처리를 삽입해야 한다는 문제점이 있다.

     

    이를 해소하기 위해 글로벌 단위로 예외 처리를 해주는 방법을 학습한다.

    우선 각각의 Controller에 예외 처리에 대한 '조언'을 해주는 DMakerExceptionHandler를 만들어준다.

     

    dmaker.exception.DMakerExceptionHandler

    @Slf4j
    // @RestControllerAdvice 어노테이션을 달아줌으로써 전체 Controller에 Exception 처리를
    // 적용할 수 있다.
    @RestControllerAdvice
    public class DMakerExceptionHandler {
    	ExceptionHandler(DMakerException.class)
    	public DMakerErrorResponse handleException(
                DMakerException e,
                HttpServletRequest request
        ) {
        log.error("errorCode: {}, url: {}, mesage: {}", 
                    e.getDMakerErrorCode(), request.getRequestURI(), e.getDetailMessage());
                    
        return DMakerErrorResponse.builder()
        .errorCode(e.getDMakerErrorCode())
        .errorMessage(e.getDetilMessage())
        .build();
        }
        
        @ExceptionHandler (value = {
        		// Http Request에 속하는 Method로 정의된 메서드가 아닌 다른 메서드에서 
                // 오류가 걸렸을 때 처리하는 Exception
                HttpRequestMethodNotSupportedException.class,
                // Validation 시 발생하는 오류에 대한 처리를 하는 Exception
                MethodArgumentNotValidException.class
        })
        public DMakerErrorResponse handleException(
                DMakerException e,
                HttpServletRequest request
        ) {
        log.error("errorCode: {}, url: {}, mesage: {}", 
                    e.getDMakerErrorCode(), request.getRequestURI(), e.getMessage());
                    
        return DMakerErrorResponse.builder()
                .errorCode(DMakerErrorCode.INVALID_REQUEST)
                .errorMessage(INVALID_REQUEST.getMessage())
                .build();
        } 
    }

     위와 같이 글로벌한 Exception 처리를 삽입해주면 Controller에 직접 Exception Handler를 넣어주지 않아도 Exception에 대한 처리를 할 수가 있다.

     

    여기에 더해서 각종 라이브러리에서 발생하는 Exception에 대한 처리도 추가해준다.

     

    dmaker.exception.DMakerExceptionController

    @Slf4j
    @RestControllerAdvice
    public class DMakerExceptionHandler {
    	ExceptionHandler(DMakerException.class)
    	public DMakerErrorResponse handleException(
                DMakerException e,
                HttpServletRequest request
        ) {
        log.error("errorCode: {}, url: {}, mesage: {}", 
                    e.getDMakerErrorCode(), request.getRequestURI(), e.getDetailMessage());
                    
        return DMakerErrorResponse.builder()
        .errorCode(e.getDMakerErrorCode())
        .errorMessage(e.getDetilMessage())
        .build();
        }
        
        @ExceptionHandler (value = {
                HttpRequestMethodNotSupportedException.class,
                // Validation 시 발생하는 오류에 대한 처리를 하는 Exception
                MethodArgumentNotValidException.class
        })
        public DMakerErrorResponse handleException(
                DMakerException e,
                HttpServletRequest request
        ) {
        log.error("errorCode: {}, url: {}, mesage: {}", 
                    e.getDMakerErrorCode(), request.getRequestURI(), e.getMessage());
                    
        return DMakerErrorResponse.builder()
                .errorCode(DMakerErrorCode.INVALID_REQUEST)
                .errorMessage(INVALID_REQUEST.getMessage())
                .build();
        }
        
        // 이 부분을 추가해준다.
        @ExceptionHandler (Exception.class)
        public DMakerErrorResponse handleException(
                Exception e, HttpServletRequest request
        ) {
        log.error("errorCode: {}, url: {}, mesage: {}", 
                    e.getDMakerErrorCode(), request.getRequestURI(), e.getMessage());
                    
        return DMakerErrorResponse.builder()
                .errorCode(INTERNAL_SERVER_ERROR)
                .errorMessage(INTERNAL_SERVER_ERROR.getMessage())
                .build();
        } 
    }

     

     

    본 포스팅은 패스트 캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
    https://bit.ly/3FVdhDa

     

    수강료 100% 환급 챌린지 | 패스트캠퍼스

    딱 5일간 진행되는 환급챌린지로 수강료 100% 환급받으세요! 더 늦기전에 자기계발 막차 탑승!

    fastcampus.co.kr

    댓글

Designed by Tistory.