Error Response JSON[프론트]


{
 "success": false,
 "httpMethod": “POST”,
 "statusCode": 400,
 "code" : "u001"
 "data": { 
		{
		  "message": " Invalid Input Value",
		  "status": 400,
		  // "errors":[], 비어있을 경우 null 이 아닌 빈 배열을 응답한다. 
		  "errors": [
		    {
		      "field": "name.last",
		      "value": "",
		      "reason": "must not be empty"
		    },
		    {
		      "field": "name.first",
		      "value": "",
		      "reason": "must not be empty"
		    }
		  ],
		}
  } 
}

ErrorException 추가 [간단 사용법]

  1. ErrorCode 정의 → enum 값을 만들어준다.
  2. GlobalException 메서드 추가
    1. ErrorResponse response 객체 생성
    2. ResponseEntityresponse, HttpStatus값을 넣어 반환해주면 된다.

BusinessException 추가 [사용 예시]

ex) **Entity**를 찾지 못하는 경우의 Exception 생성 예시

  1. ErrorCode를 먼저 정의 해줍니다.

    @Getter
    public enum ErrorCode {
     ...
     //404
     ENTITY_NOT_FOUND(HttpStatus.NOT_FOUND, "해당 엔티티를 찾을 수 없습니다.");
     ...
    }
    
  2. **EntityNotFoundException**을 **exception 패키지 하위**에 상속 받는 클래스로 생성해준다.

// BusinessException을 상속받으므로 Constructor를 만들어 주기만 하면 된다. 
public class EntityNotFoundException extends BusinessException{

    public EntityNotFoundException(String message, ErrorCode errorCode) {
        super(message, errorCode);
    }

    public EntityNotFoundException(ErrorCode errorCode) {
        super(errorCode);
    }

    //ErrorCode에서 만든 예외 enum값을 넘겨준다. 
		public EntityNotFoundException() {
        super(ErrorCode.ENTITY_NOT_FOUND);
    }
}
  1. 이렇게 정의 하면 **GlobalException.class**에서 한번에 처리를 할 수 있다. (아래 따로 추가 필요 X)
// 모든 BusinessException은 여기서 예외처리된다.
@ExceptionHandler(BusinessException.class)
	  protected ResponseEntity<ErrorResponse> handleEntityNotFoundException(final BusinessException e) {
        log.error("handleBusinessException", e);
        final ErrorCode errorCode = e.getErrorCode();
        final ErrorResponse response = ErrorResponse.of(errorCode);
        return new ResponseEntity<>(response, errorCode.getStatus());
    } 

소스 설명

Untitled

ErrorCode.class (에러 코드 정의)