How do I customize default error message from spring @Valid validation?

前端 未结 10 857
孤街浪徒
孤街浪徒 2020-12-22 23:04

DTO:

public class User {

    @NotNull
    private String name;

    @NotNull
    private String password;

    //..
}

Controller:

10条回答
  •  一整个雨季
    2020-12-22 23:46

    I know this is kind of old question,

    But I just run into it and I found some pretty good article which has also a perfect example in github.

    Basically it uses @ControllerAdvice as Spring documentation suggests.

    So for example catching 400 error will be achieved by overriding one function:

    @ControllerAdvice
    public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
    
        @Override
        protected ResponseEntity handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
            logger.info(ex.getClass().getName());
            //
            final List errors = new ArrayList();
            for (final FieldError error : ex.getBindingResult().getFieldErrors()) {
                errors.add(error.getField() + ": " + error.getDefaultMessage());
            }
            for (final ObjectError error : ex.getBindingResult().getGlobalErrors()) {
                errors.add(error.getObjectName() + ": " + error.getDefaultMessage());
            }
            final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
            return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
        }
    }
    
    
    

    (ApiError class is a simple object to hold status, message, errors)

    提交回复
    热议问题