SpringValidator美化验证不通过的返回

 关注的一点:Spring抛出的异常类型是MethodArgumentNotValidException。

package com.yufan.all.valid;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

//@ControllerAdvice
//@Component
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕捉验证失败的异常
     * 美化验证失败提示
     * @param exception
     * @return
     */

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handle(MethodArgumentNotValidException exception) {

        log.info("捕获校验异常");
        if(exception instanceof MethodArgumentNotValidException){
            BindingResult bindingResult = exception.getBindingResult();

            String errorMessage="";
            List fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError:fieldErrors){
                errorMessage +=fieldError.getDefaultMessage()+",";
            }
            String finalErrorMessage=errorMessage.substring(0,errorMessage.length()-1);
            log.info(finalErrorMessage);
            return finalErrorMessage ;
        }else{return null;}

    }
}

 

你可能感兴趣的:(SpringValidator美化验证不通过的返回)