예외처리 : Exception Handler

@ExceptionHandler : @Controller, @Restcontroller가 적용된 하나의 api에서 발생하는 예외를 잡는다. 인자로 캐치하고 싶은 예외클래스를 등록.
@ControllerAdvice : 모든 @Controller의 예외를 잡는다.
@RestControllerAdvice : @ControllerAdvice + @ResponseBody, 즉 객체 리턴이 필요할 경우.

 

[Controller]
@RestController
public class TestController {

pulbic testResponse requestTest(@RequestBody testRequest request) throws CustomException {
        if ( ~ ) {
            logger.warn("[TestController] 수행 불가 요청");
            throw new CustomException("ER9999"); // 요청내용을 처리할 수 없습니다.
        }
    }
}

[CustomException]
public class CustomException extends Excetpion {
    private String errorNo = "";
    private String errorMsg = "";

    public CustomException() {}

    public CustomException(String errorNo) {
        super(errorNo);
        this.errorNo = errorNo;
    }

    public CustomException(String errorNo, String errorMsg) {
        super(errorNo);
        this.errorNo = errorNo;
        this.errorMsg = errorMsg;
    }

    //getter, setter 생략
}

[ExceptionHandler]
@ControllerAdvice
public class CustomExceptionHandler {
    
    @ExceptionHandler(CustomException.class) {
        public ResponseEntity<PubResponse> customHandle(CustomException e) {
            PubResponse resp = new PubResponse(); //POJO
            resp.setCode(e.getErrorNo);
            resp.setMessage(e.getErrorMsg);

            return new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

 


reference

https://jeong-pro.tistory.com/195

'┝ 개발 언어 > ┎ JAVA' 카테고리의 다른 글

java7, java8에서 split("") method  (0) 2022.07.12
[file] 엑셀 파일 업로드 / 다운로드  (0) 2022.06.21
생성자와 메모리 할당  (0) 2022.05.11
restTemplate  (0) 2022.05.11
전자카드 서버 동시성 제어  (0) 2022.04.10