728x90
반응형
@RestControllerAdvice를 사용해 모든 Controller에 대한 예외 처리를 한 곳에서 관리 및 처리
*공통 에러 메시지 및 이외 예외들을 공통 처리 하는 예제
*자세한 설명 생략
▷ @RestControllerAdvice란?
- Application 전역 예외 처리 Annotation
- Project 하나의 @ControllerAdvice만 관리하는 것을 권장
- @Controller Annotation이 붙은 Controller에서 발생하는 예외를 처리
- @ResponseBody가 있어 JSON 응답
*@ControllerAdvice 차이
- @ExceptionHandler를 통해 처리
*Method 범위 Exception 처리
▷ 사용 예제
*공통 에러 메시지 설정
*이외 4XX, 500 Server Error 공통 처리
*클라이언트의 잘못된 요청으로 테스트
- CmmExceptionHandler.java
*@ExceptionHandler를 통해 어떤 Exception에 대해 어떻게 처리를 할 건지 작성
*@ExceptionHandler를 작성하지 않으면 기존에 처리하던 방식 그대로 적용
package bhs.bhsapi.cmm.util;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import bhs.bhsapi.cmm.service.vo.CmmResVO;
/**
* Application Exception Handler
*/
@RestControllerAdvice
public class CmmExceptionHandler {
/** 에러 메세지 생성 */
/** 9001 : __ 값을 확인 해주세요. */
public CmmResVO ERR_9001(String fieldName, CmmResVO resVO) { return resVO.setResCmmResult("9001", CmmUtil.nullCheck(fieldName) ? "요청 값을 확인 해주세요." : fieldName + " 값을 확인 해주세요."); }
/** 9002 : 조회 결과 값이 없습니다. */
public CmmResVO ERR_9002(CmmResVO resVO) { return resVO.setResCmmResult("9002", "조회 결과 값이 없습니다."); }
/** 9003 : 아이디를 확인 해주세요. */
public CmmResVO ERR_9003(CmmResVO resVO) { return resVO.setResCmmResult("9003", "아이디를 확인 해주세요."); }
/** 9004 : 패스워드를 확인 해주세요. */
public CmmResVO ERR_9004(CmmResVO resVO) { return resVO.setResCmmResult("9004", "패스워드를 확인 해주세요."); }
/** 9005 : 토큰 값을 확인 해주세요. */
public CmmResVO ERR_9005(CmmResVO resVO) { return resVO.setResCmmResult("9005", "토큰 값을 확인 해주세요."); }
/** 9006 : 토큰이 만료 됐습니다. 다시 로그인 해주세요. */
public CmmResVO ERR_9006(CmmResVO resVO) { return resVO.setResCmmResult("9006", "토큰이 만료 됐습니다. 다시 로그인 해주세요."); }
/** 9999 : 서버 에러가 발생했습니다. */
public CmmResVO ERR_9999(CmmResVO resVO) { return resVO.setResCmmResult("9999", "서버 에러가 발생했습니다."); }
/** 이외 에러 메세지 생성 */
@ExceptionHandler(Exception.class)
public CmmResVO handleException(Exception e, HttpServletRequest req) {
CmmUtil.errLogStamp(req.getRequestURI(), e.getMessage());
return new CmmResVO().setResCmmResult("9999", e.getMessage());
}
}
▷ 결과 확인
*클라이언트의 잘못된 요청
{
aaa
}
▷ 참고
728x90
728x90
'▶ Back-End > Java' 카테고리의 다른 글
RestTemplate Post 요청 보내기 (0) | 2024.07.04 |
---|---|
LocalDate Jackson Data Format 변경 (0) | 2023.11.23 |
Swagger UI Hangs on Big Json Respones 해결 방법 (0) | 2023.10.18 |
Swagger3 JWT 인증 설정 (0) | 2023.10.18 |
Swagger 연동 및 설정 방법 (2) | 2023.10.18 |
댓글