에러 응답 구조 체계적으로 만들기
package com.in28minnutes.rest.webservices.restfulwebservices.exception;
import java.time.LocalDate;
public class ErrorDetails {
private LocalDate timestamp;
private String message;
private String details;
public ErrorDetails(LocalDate timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public LocalDate getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDate timestamp) {
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
@Override
public String toString() {
return "ErrorDetails [timestamp=" + timestamp + ", message=" + message + ", details=" + details + "]";
}
}
package com.in28minnutes.rest.webservices.restfulwebservices.exception;
import java.time.LocalDate;
import java.time.LocalDateTime;
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.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.in28minnutes.rest.webservices.restfulwebservices.user.UserNotFoundException;
@ControllerAdvice //이 클래스를 모든 컨트롤러에 적용, 이 프로젝트에 정의된 모든 컨트롤러, 테스트 컨트롤러를 대상으
//ExceptionHandler를 선언하는 클래스를 대상
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
@ExceptionHandler(Exception.class) //어떤 예외를 처리할것인지 정의 (Exception.class) = 발생한 모든 예외를 정의
public final ResponseEntity<ErrorDetails> handleAllExceptions(Exception ex, WebRequest request) throws Exception {
ErrorDetails errorDetails = new ErrorDetails(LocalDate.now(),
ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
잘 되었음을 확인 할 수 있다
시간까지 체크하고 싶으면 LocalDate를 LocalDateTime으로 바꿔주면 됌