Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

끄적끄적

[spring] ResponseEntityExceptionHandler를 이용한 예외처리 본문

개발

[spring] ResponseEntityExceptionHandler를 이용한 예외처리

으아아아앜 2020. 1. 7. 17:08

- 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를 생성하는 메소드이다. 오버라이딩하여 사용가능하다.

 

 

Comments