11.로그와 예외처리

리얼브로·2023년 2월 27일
0
  • Summary Note
    • 로깅 시스템은 여러가지로 사용 가능하지만 SLF4J를 로깅 인터페이스로 해서 Logback을 스프링5(스프링부트2)의 구현체로 많이 사용한다.
    • 스프링에서의 예외처리는 주로 컨트롤러 단에서 처리되며, @ControllerAdvice에서 글로벌 하게 처리될 수 있다.
    • @ControllerAdvice는 컨트롤러처럼 동작하며, 모든 예외를 처리할 수 있는 컨트롤러이다.
    • Spring boot Logging system

      • Logback framework 사용

      • 로깅 레벨
        1.TRACE 2.DEBUG 3.INFO 4.WARN 5.ERROR

      • 로그 레벨 설정

          # spring framework logging    
          logging.level.org.springframework = ERROR   
        
          # local application logging    
          logging.level.com.acomp.hello = INFO           
      • Logger 사용

          package com.somebiz.restapp;
          import org.slf4j.Logger;
          import org.slf4j.LoggerFactory;
          // other imports
        
          @RestController
          public class HomeController{
              private static final Logger logger = 
                        LoggerFactory.getLogger(HomeController.class);
        
            @GetMapping("/")                      
            public Map<String, Object> test(){
                Map<String, Object> map = new HashMap<>();
                map.put("result","Aloha");
                logger.trace("{test} trace");
                logger.debug("{test} debug");
                logger.info("{test} info");
                logger.warn("{test} warn");
                logger.error("{test} error");         
                return map;                                               
            }
          }
    • REST 어플리케이션 예외처리

      • 스프링 예외처리 방법
        • 전역처리 Global level - @ControllerAdvice
        • 컨트롤러단에서 처리 Controller level - @ExceptionHandler
        • 메소드 단위 처리 Method level - try/catch
    • @ControllerAdvice - 전역처리

      • @ControllerAdvice는 스프링 어플리케이션의 모든 예외를 처리
        • @RestController는 컨트롤러

        • @ExceptionHandler 어노테이션을 사용하여 예외를 처리할 클래스를 정의

            @ControllerAdvice   
            @RestController   
            public class GlobalExceptionHandler{
                
                @ResponseStatus(HttpStatus.BAD_REQUEST)
                @ExceptionHandler(value = BaseException.class)
                public String handleBaseException(BaseException e){
                    return e.getMessage();
                }
          
                @ExceptionHandler(value = Exception.class)
                public String handleBaseException(Exception e){
                    return e.getMessage();
                }              
            }
        • GlobalExceptionHandler v2

            @ControllerAdvice   
            @RestController   
            public class GlobalExceptionHandler{
                
                @ExceptionHandler(value = ArithmeticException.class)
                public Map<String, String> handleArithMaticException(ArithmeticException e){
                    Map<String, String> res = new HashMap<>();
                    res.put("errorMsg", e.getMessage());
                    res.put("status", "error");
                    return res;
                }
          
                @ExceptionHandler(value = Exception.class)
                public Map<String, String> handleException(Exception e){
                    Map<String, String> res = new HashMap<>();
                    res.put("errorMsg", e.getMessage());
                    res.put("status", "error");
                    return res;
                }              
            }          
    • @ExceptionHandler 를 사용한 컨트롤러 단 예외처리

      • HomeController.java 파일 내에 다음 코드가 있으면, 해당 컨트롤러의 모든 NumberFormatException 을 잡아서 처리한다.
          @ExceptionHandler(value = NumberFormatException.class)
          public String nfeHandler(NumberFormatException e){
              return e.getMessage();
          }         
    • 비지니스 예외 예제

      • 명시적 예외처리가 필요 없는 RuntimeException 타입으로 작성
        public class ClientException extends RuntimeException{
            private final int errorCode;
            private final String errorDescription;
      
            public ClientException(ApiError error){
                super(error.getErrorCode() + ": "+ error.getDescription());
                this.errorCode = error.getErrorCode();
                this.errorDescription = error.getDescription();
            }
      
            public int getErrorCode(){
                return errorCode;
            }
      
            public String getErrorDescription(){
                return errorDescription;
            }
        }

0개의 댓글