본문 바로가기
▶ Back-End/Java

@RestControllerAdvice - 전역 예외 처리

by 오늘도 코딩 2023. 11. 17.
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
}

 

① 기존 응답(왼쪽), 변경된 응답(오른쪽)

 

 

▷ 참고

 

[Spring] 전역 예외 처리를 위한 @ControllerAdvice와 @RestControllerAdvice

목표 전역 예외처리를 위한 @ControllerAdvice와 @RestControllerAdvice에 대해서 알아보겠습니다. 개요 진행하던 프로젝트에서 리팩토링이 시급한 부분은 전체적인 구조였습니다. 복잡하고 가독성 떨어지

chanos.tistory.com

 

[Spring] @RestControllerAdvice + @ExceptionHandler 로 커스텀 예외처리 하기

@RestControllerAdvice + @ExceptionHandler 란? Spring에서 예외 처리를 할 때 Global 영역에서 관리해 주는 기능으로 @ControllerAdvice, @RestControllerAdvice를 사용합니다. 먼저 각 어노테이션 별로 간단하게 짚고 넘어

sasca37.tistory.com

 

 

728x90
728x90

댓글