springboot参数校验统一异常返回

一、添加依赖

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

二、注解说明

springboot参数校验统一异常返回_第1张图片

三、对实体类进行校验

1、do
@Data
public class User {
    @NotNull(message = "用户账号不能为空")
    @Size(min = 6, max = 11, message = "账号长度必须是6-11个字符")
    private String account;

    @NotNull(message = "用户密码不能为空")
    @Size(min = 6, max = 11, message = "密码长度必须是6-16个字符")
    private String password;
}

2、controller
@RestController
public class UserController {

    @PostMapping("/CreateUser")
    public void CreateUser(@RequestBody @Validated User user) {
		 System.out.println("hello");
    }
}

3、编写全局统一异常处理
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author master
 */
@RestControllerAdvice
public class ExceptionConfig {

    /**
     * 参数为实体类
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object handleValidException(MethodArgumentNotValidException e) {
      JSONObject json = new JSONObject();
        json.put("path", req.getRequestURI());
        String defaultMessage = exception.getBindingResult().getFieldError().getDefaultMessage();
        json.put("code",400);
        json.put("success", false);
        json.put("msg",defaultMessage);
        json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return json;
    }

    /**
     * 参数为单个参数或多个参数
     * @param e
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public String handleConstraintViolationException(ConstraintViolationException e) {
         //获取参数校验异常message
        String message = exception.getLocalizedMessage().split(": ")[1];
        JSONObject json = new JSONObject();
        json.put("path", req.getRequestURI());
        json.put("code",400);
        json.put("success", false);
        json.put("msg",message);
        return json;
    }
     /**
     * 普通的参数传递的形式;
     * @author  khy
     * @createTime 2021年5月18日下午5:25:16
     * @param req
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = BindException.class)
    public Object validatedGetException(HttpServletRequest req, BindException exception){
        JSONObject json = new JSONObject();
        json.put("path", req.getRequestURI());
        String defaultMessage = exception.getBindingResult().getFieldError().getDefaultMessage();
        json.put("code",400);
        json.put("success", false);
        json.put("msg",defaultMessage);
        json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return json;
    }

}

四、针对单个参数进行校验

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;

@RestController
@Validated
public class UserController {

    @PostMapping("/query")
    public void query(@NotNull(message = "id不能为空") Integer id) {
    }
}

五、配置Springboot校验模式

package com.zkzx.layer.config;

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * @Description  配置Springboot校验模式
 * @Author tianjiaxin
 * @Date 2022/07/06
 */
@Configuration
public class ValidatorConfig {

    /**
     * validation默认会校验完所有字段,然后返回所有的验证失败信息。
     * 可以通过一些简单的配置,开启Fail Fast模式,只要有一个验证失败就立即返回
     */
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation
                .byProvider(HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }

}



你可能感兴趣的:(springboot,spring,boot,java,后端)