728x90
목적
: Global Exception Advice에 설정한 예외 처리 외에, 특정 에러를 처리하고 싶은 경우에 추가하여 사용
예제 코드
(1, 2번이 있다면, 3번의 템플릿 코드만 추가하여 사용하면 됨)
1. ErrorResponse
더보기
package backend.global.exception.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import org.springframework.http.HttpStatus;
@Getter
@AllArgsConstructor @Builder
public class ErrorResponse {
private int status; // 에러코드번호
private String exception; // 예외명 (예외 분류)
private String message; // 에러메세지
// 에러 처리
public static ErrorResponse of(HttpStatus httpStatus) {
return new ErrorResponse(httpStatus.value(), httpStatus.getReasonPhrase());
}
// 에러 응답
private ErrorResponse(int status, String message) {
this.status = status;
this.message = message;
}
}
2. ExceptionAdvice
더보기
package backend.global.exception.advice;
import backend.global.exception.dto.BusinessLogicException;
import backend.global.exception.dto.ErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@RestControllerAdvice @Slf4j
public class ExceptionAdvice {
// 일반 에러 처리
@ExceptionHandler
public ResponseEntity<ErrorResponse> ExceptionHandler(Exception e) {
ErrorResponse errorResponse = new ErrorResponse(400, e.getClass().getSimpleName(), "잘못된 요청입니다.");
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
// 비즈니스 로직(Service) 에러 처리
// 새로운 비즈니스로직에러는 ExceptionCode Enum에 추가하여 사용
@ExceptionHandler
public ResponseEntity BusinessLoginExceptionHandler (BusinessLogicException e) {
ErrorResponse errorResponse = new ErrorResponse(e.getExceptionCode().getStatus(), // 보내줄 에러 정보들 (현재 3가지만 선정)
e.getClass().getSimpleName(),
e.getExceptionCode().getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(e.getExceptionCode().getStatus())); // 보내준 에러코드
}
}
3. 템플릿 코드
package backend.global.exception.advice;
...
@RestControllerAdvice @Slf4j
public class ExceptionAdvice {
...
// 추가적으로 필요한 예외 처리시, 에러 응답을 따로 빌드하여 사용하기 위한 추가 템플릿 코드
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ErrorResponse> handleHttpMessageNotReadableException(
HttpServletRequest request,
HttpMessageNotReadableException e) {
log.error("handleHttpMessageNotReadableException : {}", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
ErrorResponse.builder()
.status(400)
.exception(HttpStatus.BAD_REQUEST.getReasonPhrase())
.message("항목을 모두 작성해주세요.")
.build()
);
}
}
참고글
1. Exception코드 auditing 세팅 : https://radpro.tistory.com/3782
2. Custom Exception 만들기 : https://radpro.tistory.com/225
3. Spring MVC 예외처리 1 : https://radpro.tistory.com/220
4. Spring MVC 예외처리 2 : https://radpro.tistory.com/221
5. Spring MVC 예외처리 3 : https://radpro.tistory.com/222
728x90
'Java & Spring > 옵션정리' 카테고리의 다른 글
[SpringBoot] Security 설정을 이용한 Member / Admin Role_DB 분리 (0) | 2022.11.28 |
---|---|
[Java] double을 long타입으로 형변환 (0) | 2022.11.25 |
[SpringBoot] LocalDateTime으로 시간 계산하기 (0) | 2022.11.25 |
[SpringBoot] Login애너테이션 설정 (0) | 2022.11.22 |
[AWS] EC2 명령어 (0) | 2022.11.22 |