inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 MVC 2편 - 백엔드 웹 개발 활용 기술

@ControllerAdvice

커스텀 익셉션을 만들어볼려고 합니다.

259

인프러너

작성한 질문수 58

2

@Data
@AllArgsConstructor
public class ErrorResult {
    private String code;
    private String message;
    private Map<String, Object> map;
}
@Slf4j
@RestControllerAdvice
public class ExControllerAdvice {

    @ExceptionHandler
    public ResponseEntity<ErrorResult> userExHandler(UserException e, Map<String, Object> map) {
        log.error("[exceptionHandler] ex", e);
        ErrorResult errorResult = new ErrorResult("USER-EX", e.getMessage(), map);
        return new ResponseEntity(errorResult, HttpStatus.BAD_REQUEST);
    }

}
public class UserException extends RuntimeException {

    public UserException() {
        super();
    }

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

    public UserException(String message, Throwable cause) {
        super(message, cause);
    }

    public UserException(Throwable cause) {
        super(cause);
    }

    protected UserException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

이렇게 만들고 컨트롤러에서 사용을 할려고

...
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("errorTitle", "titleMsg");
                throw new UserException("ERROR", returnMap);
...

이런식으로 만들었는데
UserException 클래스에서 두 번째 파라미터로 받는 부분이 Throwable 타입이라 오류가 발생되는데..
혹시 두번째 파라미터에 맵이나 리스트나 String등 원하는 값을 받아서 ResponseEneity 타입으로 보내줄려고 하면 어떻게 수정을 해야할까요?

UserException을 아래처럼 수정을 했는데

    public UserException(String message, Map<String, Object> map) {
        super(message);
        this.map = map;
    }

포스트맨으로 테스트를 해 보면 원하는 에러코드가 출력되는게 아니라 기본적인 오류코드가 출력이 되어버리네요..

spring MVC

답변 1

2

김영한

안녕하세요. 아버지님

UserException 안에 Map으로 데이터를 저장해두고, ExControllerAdvice에서 UserException안에 있는 Map을 꺼내서 활용하시면 됩니다.

감사합니다.

0

인프러너

답변 감사합니다.

말씀하신 내용중 Map으로 데이터를 저장해두는게 아래와 같이 map으로 데이터를 받아오는것 말고 다른내용일까요?

    public UserException(String message, Map<String, Object> map) {
        super(message);
        this.map = map;
    }

 

그리고 UserException 안에 있는 Map을 꺼내서 활용한다는게 아래 소스에서 map으로 받아와서 처리를 하는것이 아닐까요??

@Slf4j
@RestControllerAdvice
public class ExControllerAdvice {

    @ExceptionHandler
    public ResponseEntity<ErrorResult> userExHandler(UserException e, Map<String, Object> map) {
        log.error("[exceptionHandler] ex", e);
        ErrorResult errorResult = new ErrorResult("USER-EX", e.getMessage(), map);
        return new ResponseEntity(errorResult, HttpStatus.BAD_REQUEST);
    }

}

 

정확하게 어떤내용인지를 이해가 잘 가지 않은데 혹시 조금만 더 자세하게 설명 부탁드려도 될까요?

2

김영한

UserException 안에 Map을 저장해두시고, 예를 들면 다음과 같이 꺼내서 사용하시면 됩니다

    @ExceptionHandler
    public ResponseEntity<ErrorResult> userExHandler(UserException e) {
        log.error("[exceptionHandler] ex", e);
        Map map = e.getMap(); //여기 확인
        ErrorResult errorResult = new ErrorResult("USER-EX", e.getMessage(), map);
        return new ResponseEntity(errorResult, HttpStatus.BAD_REQUEST);
    }

이미지 업로드와 db 트랜잭션 묶는법

0

43

1

Could not resolve org.springframework.boot:spring-boot-starter-validation:2.4.4

0

53

2

MessageSourceTest 코드

0

49

1

인터셉터 에러 설정

0

48

1

resolveArgument()메서드 질문

0

57

1

43강 검증1 에서 실패 로직 관련 질문있습니다.

0

58

2

타임리프 3.X 버전 rendering, serializer 에러 해결 방법

2

133

3

스프링 빈에 등록이 안되는거 같은데 어떻게 하면 좋을까요?ㅠㅠ

0

90

3

pdf 오타 문의

0

57

1

ItemUpdateForm 검증 관련 질문입니다.

0

49

1

22page 링크 주소 변경

0

59

2

특정 데이터와 파일을 함께 저장 시, 테이블 구조 질문

0

53

1

섹션3번 수업에 대한 질문입니다.

0

80

2

@Autowired 보다 더 좋은 방법이 어떤 걸까요?

0

85

2

타입컨버터 가 람다랑 비슷해 보이는데 저의 생각이 맞는지?.

0

66

1

자바스크립트 인라인에서 객체 직렬화 시 오류가 납니다

0

142

3

스프링부트 - 오류페이지2 에서 500.html 에서 쓰인 객체 질문

0

63

1

톰캣 에러 페이지가 안보입니다.

0

104

2

apiEceptionController에서 센드 에러 호출하면 안되는지?

0

81

1

세션 타임아웃시 쿠키 삭제 방법이 없나요?

0

118

2

ApiExceptionController 질문드립니다.

0

64

1

셀렉박스 챕터에서 option value에 ==배송 방식 선택== 이것을 넣은 이유가 궁금함, 이렇게 구상해도 되는지?

0

66

1

MemberRepository 필드의 fianl 선언 유무

0

85

2

혹시 index.html 에서는 fragment 사용이 안되는건가요

0

58

1