一、先编写一个测试的实体类
编写一个测试类,并在需要校验的字段上加上相关的注解
例:在name上加上了非空的校验
* @author xxzheng
* @email xuxiangzheng@gmail.com
* @date 2022-11-30 15:59:43
*/
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 品牌id
*/
@TableId
private Long brandId;
/**
* 品牌名
*/
@NotBlank
private String name;
/**
* 品牌logo地址
*/
private String logo;
/**
* 介绍
*/
private String descript;
}
二、编写一个Controller测试类
编写一个测试类并在需要校验的接口上加上@Vaild注解
package com.atguigu.gulimall.product.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import javax.validation.Valid;
/**
* @author xxzheng
* @email xuxiangzheng@gmail.com
* @date 2022-11-30 15:59:43
*/
@RestController
@RequestMapping("product/brand")
public class BrandController {
@Autowired
private BrandService brandService;
/**
* 保存
*/
@RequestMapping("/save")
public R save(@Valid @RequestBody BrandEntity brand){
brandService.save(brand);
return R.ok();
}
}
三、编写一个统一处理异常的异常类
编写一个同意处理异常的的异常类,用于记录异常日志并且返回结果。
package com.atguigu.gulimall.product.exception;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
/**
* @program: com.atguigu.gulimall.product.exception
* @description:集中处理所有异常
* @author: xxzherng
* @create: 2022-12-28 16:46
**/
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleValidException (MethodArgumentNotValidException e){
log.info("数据校验出现异常{},异常类型{}",e.getMessage(),e.getClass());
BindingResult bindingResult = e.getBindingResult();
HashMap<String, String> errorMap = new HashMap<>();
bindingResult.getFieldErrors().forEach((fieldError -> {
errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
}));
return R.error(400,"数据校验出现问题").put("data",errorMap);
}
}
四、使用postman联调工具进行测试
使用postman进行联调测试观察结果