본문 바로가기
프로젝트/SNS 프로젝트

[회원정보 수정] 글로벌 예외처리

by 영카이브 2024. 3. 29.

글로벌 예외 처리(Global Exception Handling)란? 

 

애플리케이션에서 발생하는 모든 예외를 중앙 집중적으로 처리하는 방식

예외 처리 코드를 각각의 컨트롤러나 서비스 메서드마다 반복해서 작성하는 것을 피하고, 일관된 방식으로 예외를 처리할 수 있도록 한다. 

 

일반적으로 웹 애플리케이션에서는 예외가 발생하면 HTTP 응답 코드와 함께 에러 페이지를 반환한다. 그러나 글로벌 예외 처리를 구현하면 예외를 캐치하고 일반적인 형식으로 에러 응답을 반환하는 중앙 집중식의 예외 처리 로직을 구현할 수 있다. 

 

 

글로벌 예외 처리의 주요 목적

  1. 일관성 있는 에러 응답
  2. 중복 코드 제거
  3. 애플리케이션 로직과 분리: 글로벌 예외 처리는 애플리케이션의 핵심 로직과 예외 처리 로직을 분리하여 코드의 가독성을 높이고 유지보수를 쉽게 한다.
  4. 로그 및 모니터링: 예외가 발생할 때 로그를 기록하고 관리자에게 경고를 보내는 등의 추가적인 작업을 수행할 수 있다.

 

UserService 추가

User userEntity = userRepository.findById(id)
			    .orElseThrow(() -> new CustomValidationApiException("찾을 수 없는 id입니다."));

 

적용

@RequiredArgsConstructor
@Service
public class UserService {

	private final UserRepository userRepository; 
	private final BCryptPasswordEncoder bCryptPasswordEncoder; 
	
	@Transactional
	public User 회원수정(int id,User user) {
		// 1. 영속화
		// (1) get(): 무조건 찾았다.걱정마
		// (2) orElseThrow(): 못찾았으니 exception 발동 
		User userEntity = userRepository.findById(id)
			    .orElseThrow(() -> new CustomValidationApiException("찾을 수 없는 id입니다."));

		
		// 2. 영속화된 오브젝트 수정
		userEntity.setName(user.getName());
		String rawPassword = user.getPassword();
		String encPassword = bCryptPasswordEncoder.encode(rawPassword);
		
		userEntity.setPassword(encPassword);
		userEntity.setBio(user.getBio());
		userEntity.setWebsite(user.getWebsite());
		userEntity.setPhone(user.getPhone());
		userEntity.setGender(user.getGender());
		return userEntity; 
		// 수정이 끝나면 더티체킹이 일어나서 업데이트 완료
	}
}

 

CustomValidationApiException 추가

	public CustomValidationApiException(String message) {
		super(message);
	}

 

적용

public class CustomValidationApiException extends RuntimeException{

	// 객체를 구분하기 위해 시리얼넘버를 넣어주는것
	// JVM을 위해 걸어주는 것 
	private static final long serialVersionUID = 1L;

	// 유효성 검사 실패 시 발생한 에러메세지를 담은 맵
	private Map<String, String> errorMap;
	
	// 생성자로 전달된 메세지와 에러맵을 사용해 예외객체 생성
	public CustomValidationApiException(String message) {
		super(message);
	}
	
	// 생성자로 전달된 메세지와 에러맵을 사용해 예외객체 생성
		public CustomValidationApiException(String message,Map<String, String> errorMap) {
			super(message);
			this.errorMap = errorMap; 
		}
	
	// 에러메세지를 담은 맵을 반환하는 메서드
	public Map<String, String> getErrorMap(){
		return errorMap;
	}
	
}

 

update.js

// (1) 회원정보 수정
function update(userId, event) {
	event.preventDefault(); //폼태그 액션막기
    let data = $("#profileUpdate").serialize(); 
    console.log(data);
    // 데이터를 응답해줘야한다.
    $.ajax({
        type: "put",
        url: "/api/user/" + userId,
        data: data,
        contentType: "application/x-www-form-urlencoded; charset=utf-8", // contentType의 오타 수정
        dataType: "json"
    }).done(res => { //HtttpStatus 상태코드 200번대
        console.log("update 성공", res);
       	location.href ="/user/"+ userId;
    }).fail(error => { //HtttpStatus 상태코드 200번대가 아닐 때 
   		console.log(error); 
   		if(error.data==null){
			alert(error.responseJSON.message);
		} else {
			// 자바스크립트를 JSON으로 변경
    		alert(JSON.stringify(error.responseJSON.data));
		}
		  
    	
    });
}