
1. ApiUtil 만들기
- 200 : 정상
- 300 : 리다이렉션
- 400 : 유효성 검사 실패시
- 403 : 권한 없음
- 500 : 서버측 오류
- http 상태코드도 심어줘야 함

package shop.mtcoding.blog._core.utils;
import lombok.Data;
@Data
public class ApiUtil<T> {
private Integer status ; //200,400,404,405
private String msg ; // 성공, 실패 -> 메세지 성공시에는 메세지 필요없음
private T body ; // 타입이 정해져있지 않아 new 때 타입을 정하는 T로 정함
//통신이 성공했을 때
public ApiUtil(T body) {
this.status = 200;
this.msg ="성공";
this.body = body;
}
//통신이 실패했을 때
public ApiUtil(Integer status, String msg) {
this.status = status;
this.msg = msg;
this.body=null; // 실패 시에는 메세지와 상태코드만 필요하기 때문에 바디 데이터는 필요없다.
}
}
2. myExceptionHandler 를 json으로 반환하게 수정하기
- view 요청과 ajax 요청으로 두 개가 필요함
- 우리는 json을 요청하는 핸들러가 필요
- 제네릭은 오브젝트를 리턴

- HttpStatus : 상태 코드


package shop.mtcoding.blog._core.errors;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import shop.mtcoding.blog._core.errors.exception.*;
import shop.mtcoding.blog._core.utils.ApiUtil;
@RestControllerAdvice // RUNTIME 예외가 터지면 여기로 오류가 모여 처리함
public class myExceptionHandler {
// 커스텀 예외를 만들어서 런타임 예외 상속하기
@ExceptionHandler(Exception400.class)
public ResponseEntity<?> ex400(RuntimeException e) { // 오브젝트를 리턴
ApiUtil<?> apiUtil = new ApiUtil<>(400, e.getMessage()); // http 바디 안에서 구성한 객체 넣기
return new ResponseEntity<>(apiUtil, HttpStatus.BAD_REQUEST); // http의 헤더와 바디 넣기
}
@ExceptionHandler(Exception401.class)
public ResponseEntity<?> ex401(RuntimeException e) {
ApiUtil<?> apiUtil = new ApiUtil<>(401, e.getMessage());
return new ResponseEntity<>(apiUtil, HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(Exception403.class)
public ResponseEntity<?> ex403(RuntimeException e, HttpServletRequest request) {
ApiUtil<?> apiUtil = new ApiUtil<>(403, e.getMessage());
return new ResponseEntity<>(apiUtil, HttpStatus.FORBIDDEN);
}
@ExceptionHandler(Exception404.class)
public ResponseEntity<?> ex404(RuntimeException e, HttpServletRequest request) {
ApiUtil<?> apiUtil = new ApiUtil<>(404, e.getMessage());
return new ResponseEntity<>(apiUtil, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception500.class)
public ResponseEntity<?> ex500(RuntimeException e, HttpServletRequest request) {
ApiUtil<?> apiUtil = new ApiUtil<>(500, e.getMessage());
return new ResponseEntity<>(apiUtil, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Share article