Spring boot로 REST API 개발 시 요청 데이터 Validation을 위한 ControllerAdvice의 Exception Handling
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<Response<Object>> notValidRequestData(HttpServletRequest request, HttpMessageNotReadableException e) {
if(e.getRootCause() instanceof InvalidFormatException) {
// invalid json format
} else {
// another format error
}
}
@ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
public ResponseEntity<Response<Object>> badRequest(HttpServletRequest request, Exception e) {
BindingResult bindingResult = null;
if(e instanceof BindException) {
// Validated by @Valid
bindingResult = ((BindException) e).getBindingResult();
} else if(e instanceof MethodArgumentNotValidException) {
// Validated by @Validated for @RequestParam validatation
bindingResult = ((MethodArgumentNotValidException)e).getBindingResult();
}
if(bindingResult != null) {
FieldError fieldError = bindingResult.getFieldError();
// not valid field name
String fieldName = fieldError.getField();
// requested value
Object requestedValue = fieldError.getRejectedValue();
// if set message on @Valid, it override that setted message.
String errorMessage = fieldError.getDefaultMessage();
}
}
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<Response<Object>> badRequestMissingParameter(HttpServletRequest request, MissingServletRequestParameterException e) {
String parameterName = e.getParameterName();
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<Response<Object>> badRequestInvalidDataParameter(HttpServletRequest request, MethodArgumentTypeMismatchException e) {
String fieldName = e.getName()
String definedTypeClass = e.getRequiredType().getName();
String requestedTypeClass = e.getValue().getClass().getSimpleName();
}
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Response<Object>> badRequestInvalidParameter(HttpServletRequest request, ConstraintViolationException e) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
if(constraintViolations != null) {
for(ConstraintViolation c : constraintViolations) {
String pathStr = c.getPropertyPath().toString();
String[] paths = pathStr.split("\\.");
String path = paths.length > 0 ? paths[paths.length - 1] : paths[0];
String fieldName = c.getPropertyPath()
Object requestedValue = c.getInvalidValue();
String message = c.getMessage();
}
}
}