Springboot 글로벌 예외 프로세서

Springboot 글로벌 예외 프로세서


1. 글로벌 예외 프로세서 만들기

@ControllerAdvice
//  
@ResponseBody
@Slf4j
public class HandleExceptionResolver {


    //  
    @ExceptionHandler(Exception.class)
    public ApiResult resolveException(HttpServletRequest request, Exception e) throws Exception {


        log.info(" -  -- - - -- - - - -- ");
        log.info("msg : {}", e.getMessage());
        log.info("cause : {}", e.getCause());

        return new ApiResult<>().fail();

    }
}

2.ApiResult
@Data
@Slf4j
@NoArgsConstructor
@Accessors(chain = true)
public class ApiResult {


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    private static class Metadata implements Meta{
        private int code;
        private String reasonPhraseUS, reasonPhraseCN;
    }

    private Metadata metadata;

    private Timestamp currentTime;
    private T data;

    public ApiResult(Meta meta, T data) {
        metadata = new Metadata(meta.getCode(),meta.getReasonPhraseUS(),meta.getReasonPhraseCN());
        this.data = data;
        currentTime = new Timestamp(System.currentTimeMillis());
    }

    public ApiResult success(T data){
        return new ApiResult(HttpStatusEnum.OK, data);
    }

    public ApiResult fail(){
        return new ApiResult(HttpStatusEnum.INTERNAL_SERVER_ERROR, null);
    }

    public static void main(String[] args) {
        System.out.println(new ApiResult<>().success(0));
    }

}

좋은 웹페이지 즐겨찾기