Skip to content

Commit

Permalink
fix: after spring-boot upgrade HandlerMethodValidationException is us…
Browse files Browse the repository at this point in the history
…ed for validation errors
  • Loading branch information
melistik committed Apr 2, 2024
1 parent c9b781d commit b25d434
Showing 1 changed file with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import io.rocketbase.commons.exception.ErrorCodes;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
Expand All @@ -13,6 +14,9 @@
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.List;


@ControllerAdvice
Expand All @@ -23,7 +27,30 @@ public class BeanValidationExceptionHandler extends BaseExceptionHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse handleBeanValidationException(HttpServletRequest request, MethodArgumentNotValidException e) {
public ErrorResponse handleHandlerMethodValidation(HttpServletRequest request, HandlerMethodValidationException e) {
ErrorResponse result = new ErrorResponse(ErrorCodes.FORM_ERROR.getStatus(), null);
result.setMessage(translate(request, "400", e.getMessage()));

List<? extends MessageSourceResolvable> errors = e.getAllErrors();
for (MessageSourceResolvable error : errors) {
if (error instanceof FieldError fieldError) {
String code = fieldError.getCode();
String defaultMessage = fieldError.getDefaultMessage();
result.addField(fieldError.getField(), translate(request, "error.form." + code, defaultMessage));
}
}

if (log.isDebugEnabled()) {
log.debug("[{}] {} throws HandlerMethodValidationException fieldErrors: {}", request.getMethod(), request.getContextPath(), result.getFields());
}

return result;
}

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse handleMethodArgumentNotValid(HttpServletRequest request, MethodArgumentNotValidException e) {
ErrorResponse result = new ErrorResponse(ErrorCodes.FORM_ERROR.getStatus(), null);

BindingResult bindingResult = e.getBindingResult();
Expand Down

0 comments on commit b25d434

Please sign in to comment.