끄적끄적
[spring] ResponseEntityExceptionHandler를 이용한 예외처리 본문
- ExceptionHandlerAdvice 생성
@RestControllerAdvice
public class ExceptionHandlerAdvice extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
return super.handleExceptionInternal(ex, body, headers, status, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpHeaders headers, HttpStatus status, WebRequest req) {
List<ErrorContent> contentList = new ArrayList<>();
for(FieldError error : e.getBindingResult().getFieldErrors()){
contentList.add(new ValidErrorContent(
error.getField(),
error.getDefaultMessage(),
error.getRejectedValue()
));
}
return handleExceptionInternal(e,new ApiError(HttpStatus.BAD_REQUEST,contentList),new HttpHeaders(),HttpStatus.BAD_REQUEST, req);
}
}
- ResponseEntityExceptionHandler를 상속받아 관련 메소드를 사용하여 예외처리를 유용하게 가능
- @Override handleMethodArgumentNotValid() : 스프링에서 이미 정의된 예외 중 ArgumentNotValid를 처리하기 위한 메소드이다. 오버라이딩하여 원하는 로직을 작성하면 된다.
(해당 메소드 이외에도 수많은 관련 메소드가 있음으로 필요에 따라 오버라이딩하여 사용하면 됨)
만약, ResponseEntityExceptionHandler에서 이미 처리하고 있는 예외를 @ExceptionHandler로 처리하려고 한다면
"Error creating bean with name 'handlerExceptionResolver' 에러가 발생하기 때문에 주의가 필요하다.
참고 : https://stackoverflow.com/questions/56121931/error-creating-bean-with-name-handlerexceptionresolver-defined-in-class-path-r
- @Override handleExceptionInternal() : ResponseEntity를 생성하는 메소드이다. 오버라이딩하여 사용가능하다.
'개발' 카테고리의 다른 글
[spring] @Cacheable 사용하기(+ ehcache 설정) (0) | 2020.02.19 |
---|---|
[spring] @Async 사용하기 (0) | 2020.02.19 |
[intelij] properties 파일 한글처리 (0) | 2020.01.06 |
[spring] JPA properties 설정 (0) | 2019.12.26 |
[spring] database 연결 테스트 코드 (0) | 2019.12.24 |