CustomRestAdvice
페이지 정보
본문
package web.controller.advice;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import lombok.extern.log4j.Log4j2;
@RestControllerAdvice
@Log4j2
public class CustomRestAdvice {
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
public ResponseEntity<Map<String, String>> handleBindException(BindException e){
log.error(e);
Map<String, String> errorMap = new HashMap<>();
if(e.hasErrors()) {
BindingResult bindingResult = e.getBindingResult();
bindingResult.getFieldErrors().forEach(fieldError -> {
errorMap.put(fieldError.getField(), fieldError.getCode());
});
}
return ResponseEntity.badRequest().body(errorMap);
}
@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
public ResponseEntity<Map<String, String>> handleFKException(Exception e) {
log.error(e);
Map<String, String> errorMap = new HashMap<>();
errorMap.put("time", ""+System.currentTimeMillis());
errorMap.put("msg", "잘못된 경로 및 값으로 인해 실패처리");
return ResponseEntity.badRequest().body(errorMap);
}
@ExceptionHandler(NoSuchElementException.class)
@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
public ResponseEntity<Map<String, String>> handleNoSuchElement(Exception e) {
log.error(e);
Map<String, String> errorMap = new HashMap<>();
errorMap.put("time", ""+System.currentTimeMillis());
errorMap.put("msg", "rno를 찾을 수 없음. 실패");
return ResponseEntity.badRequest().body(errorMap);
}
}
- 이전글■ 데이타가 존재하지 않는 경우에 대한 예외 처리 24.06.23
- 다음글▲ localhost:8080/swagger-ui/index.html ( 댓글 조회 예외 테스트 ) 24.06.23
댓글목록
등록된 댓글이 없습니다.