해당 예외가 발생했을 때 처리해주는 어노테이션
예시
@ExceptionHandler(value = {HttpMessageNotReadableException.class})
public ResponseDto<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.error(
"handleHttpMessageNotReadableException() in GlobalExceptionHandler throw HttpMessageNotReadableException : {}", e.getMessage()
);
return ResponseDto.fail(new CommonException(ErrorCode.BAD_REQUEST_JSON));
}
//ResponseDto
public record ResponseDto<T>(
@JsonIgnore HttpStatus httpStatus,
@Schema(name = "success", description = "API 호출 성공 여부") @NotNull Boolean success,
@Schema(name = "data", description = "API 호출 성공 시 응답 데이터") @Nullable T data,
@Schema(name = "error", description = "API 호출 성공 시 응답 데이터") @Nullable ExceptionDto error) {}
Controller 단에서 발생한 예외들을 AOP 를 적용하여 전역적으로 처리하도록 해주는 어노테이션을 칭한다.
@ExceptionHandler 와 같이 사용된다.
@RestControllerAdvice @ResponseBody 에 포함되기 때문에 당연히 Json의 형태로 응답한다.
예시
@RestControllerAdvice
public class GrobalExceptionHandler{
@ExceptionHandler(value = {HttpMessageNotReadableException.class})
public ResponseDto<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.error(
"handleHttpMessageNotReadableException() in GlobalExceptionHandler throw HttpMessageNotReadableException : {}", e.getMessage()
);
return ResponseDto.fail(new CommonException(ErrorCode.BAD_REQUEST_JSON));
}
}
//ResponseDto
public record ResponseDto<T>(
@JsonIgnore HttpStatus httpStatus,
@Schema(name = "success", description = "API 호출 성공 여부") @NotNull Boolean success,
@Schema(name = "data", description = "API 호출 성공 시 응답 데이터") @Nullable T data,
@Schema(name = "error", description = "API 호출 성공 시 응답 데이터") @Nullable ExceptionDto error) {}