2 minute read

개요

Bus
💡 1.서로의 세션이 다르기 때문임을 확인 함.

구현1 : 커스텀익셉션 1depth

BusinessExceptionHandler.java : Exception 커스텀 클래스 작성

public class BusinessExceptionHandler extends RuntimeException {

	//공통적인 ErrorCode 싱글톤 객체에는 데이터를 SET 한다. 그리고
    private ErrorCode errorCode;
    
    //직접 정의한 메세지를 보내거나
    public BusinessExceptionHandler(String message, ErrorCode errorCode) {
        super(message);
        this.errorCode = errorCode;
    }

    //Error코드에 정의된 메세지를 보내거나
    public BusinessExceptionHandler(ErrorCode errorCode) {
        super(errorCode.getMessage());
        this.errorCode = errorCode;
    }

    public ErrorCode getErrorCode() {
        return errorCode;
    }

}

GlobalExceptionHandler.java : Exception 커스텀 클래스 감지 추가

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    ...
    /** [커스텀익셉션] BusinessException에서 발생한 에러 **/
    @ExceptionHandler(BusinessExceptionHandler.class)
    protected ResponseEntity<ErrorResponse> handleCustomException(final BusinessExceptionHandler e) {
        log.debug("===========================================================");
        log.debug("[handleCustomException()] 여기로 오는가?!");
        log.debug("e.getMessage(): " + e.getMessage().toString());
        log.debug("e.getErrorCode(): " + e.getErrorCode().toString());
        log.debug("===========================================================");
        final ErrorCode errorCode = e.getErrorCode();
        final ErrorResponse response = ErrorResponse.of(errorCode); //ex)ENTITY_NOT_FOUND
        return new ResponseEntity<>(response, HttpStatus.valueOf(errorCode.getStatus()));
    }
    ...
}

Exception 커스텀 클래스 감지 추가
💡 1.BusinessExceptionHandler 이라는 컨트롤러에서 발생하는 Exception 을 감지하도록 처리했다.

구현 테스트

실행

    @ResponseBody
    @RequestMapping(value = "/app/testBindException", method = RequestMethod.GET)
    public String testBindException(@RequestParam(value = "name", required = false) String name) {
        try {
            int errorCALL = tB002Service.setInsert(new TB002()); //Exception 발생
        } catch (Exception e) {
            throw new BusinessExceptionHandler(e.getMessage(), ErrorCode.INSERT_ERROR); //커스텀익셉션 예외 던지기
        }
		return "";

    }
	

서버 결과

[2024-07-21 19:26:55] DEBUG: com.blang.bck.comm.error.GlobalExceptionHandler - ===========================================================
[2024-07-21 19:26:55] DEBUG: com.blang.bck.comm.error.GlobalExceptionHandler - [handleCustomException()] 여기로 오는가?!
[2024-07-21 19:26:55] DEBUG: com.blang.bck.comm.error.GlobalExceptionHandler - e.getMessage(): 
### Error updating database.  Cause: java.sql.SQLIntegrityConstraintViolationException: Column '회원일련번호' cannot be null
### The error may involve com.blang.bck.mappers.web.TB002Mapper.TB002Insert-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO TB002 ~~ 내용
### Cause: java.sql.SQLIntegrityConstraintViolationException: Column '일련번호' cannot be null
; SQL []; Column '일련번호' cannot be null; nested exception is java.sql.SQLIntegrityConstraintViolationException: Column '일련번호' cannot be null
[2024-07-21 19:26:55] DEBUG: com.blang.bck.comm.error.GlobalExceptionHandler - e.getErrorCode(): INSERT_ERROR
[2024-07-21 19:26:55] DEBUG: com.blang.bck.comm.error.GlobalExceptionHandler - ===========================================================

브라우저 응답

{
    "status": 200,
    "code": "9999",
    "message": "Insert Transaction Error Exception",
    "errors": [],
    "reason": null
}

구현2 : 커스텀익셉션 2depth

개요

throw new BusinessExceptionHandler(e.getMessage(), ErrorCode.INSERT_ERROR); //커스텀익셉션 예외 던지기

이렇게 즉시 던지는 것은 의미가 없다. 조금 더 구조화 해보자.

EntityNotFoundException.java : 커스텀 클래스를 상속받는 세부익셉션 클래스 작성

public class EntityNotFoundException extends BusinessExceptionHandler {

	/***********************************
	 * EntityNotFoundException : 각 엔티티들을 못찾았을 경우
	 * - DAO등등.. findById, findByCode 메서드에서 조회가 안되었을 경우
	 ***********************************/
    public EntityNotFoundException(String message) {
        super(message, ErrorCode.ENTITY_NOT_FOUND);
    }
}

EntityNotFoundException.java : 커스텀 클래스를 상속받는 세부익셉션 클래스 작성

public class HOme extends BusinessExceptionHandler {

	/***********************************
	 * EntityNotFoundException : 각 엔티티들을 못찾았을 경우
	 * - DAO등등.. findById, findByCode 메서드에서 조회가 안되었을 경우
	 ***********************************/
    public EntityNotFoundException(String message) {
        super(message, ErrorCode.ENTITY_NOT_FOUND);
    }
}

Leave a comment