개발은 하는건가..

[mybatis] Sql Exception 처리 본문

SpringBoot , Thymeleaf

[mybatis] Sql Exception 처리

수동애비 2023. 9. 12. 16:42
반응형

Repository 에 다음과 같이  DataAccessException 을 throws 해준다.

@Repository
@Mapper
public interface UserRepository {
    int insertUser(UserInfoDTO uid) throws DataAccessException;
}

아래와 같이 서비스에서 Repository 함수를 호출하면서 Exception 을 catch 하여 처리해준다.


@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository _UserRepo;

    public int addUser(UserInfoDTO user) {
        int res = 0;

        try {
            user.setPwd(CryptoUtils.getSHA256(user.getPwd()));
            res = _AdminRepo.insertUser(user);
        } catch (DataAccessException e) {

            if (e instanceof DuplicateKeyException) {
                // 중복 키
                log.error("DuplicateKeyException");
                res = 1;
            }
            else if (e instanceof DataIntegrityViolationException) {
                // 허용하지 않은 필드 타입 매칭 또는 Null 허용 안함 필드 null 매칭
                log.error("DataIntegrityViolationException");
                res = 2;
            }
            else {
                log.error(e.getCause().getMessage());
                res = 3;
            }          
        }

        return res;
    }
Comments