1.JSR 303 校驗(yàn)注解
1.給Bean添加校驗(yàn)注解javax.validation.constraints
/**
* 品牌名
*/
@NotBlank(message = "品牌名必須提交")
private String name;
2.開啟校驗(yàn)功能 @Valid
/**
* 保存
*/
@RequestMapping("/save")
public R save(@Valid @RequestBody BrandEntity brand){
brandService.save(brand);
return R.ok();
}
3.給校驗(yàn)的bean后緊跟一個(gè)BindingResult,就可以獲取到校驗(yàn)的結(jié)果
/**
* 保存
*/
@RequestMapping("/save")
public R save(@Valid @RequestBody BrandEntity brand, BindingResult result){
if (result.hasErrors()) {
Map<String, String> map = new HashMap<>();
// 獲取校驗(yàn)錯(cuò)誤結(jié)果
result.getFieldErrors().forEach((item) -> {
// 獲取錯(cuò)誤信息
String message = item.getDefaultMessage();
// 獲取字段名
String field = item.getField();
map.put(field, message);
});
return R.error(400, "提交的數(shù)據(jù)不合法").put("data", map);
} else {
brandService.save(brand);
}
return R.ok();
}
2.集中處理異常
package com.agegg.gulimall.product.exception;
import com.agegg.common.exception.BizCodeEnum;
import com.agegg.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.*;
import java.util.HashMap;
import java.util.Map;
/**
* 集中處理所有異常
*/
@Slf4j
@RestControllerAdvice(basePackages = "com.agegg.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleVaildException(MethodArgumentNotValidException e) {
log.error("數(shù)據(jù)效驗(yàn)出現(xiàn)問題{},異常類型{}", e.getMessage(), e.getClass());
BindingResult result = e.getBindingResult();
Map<String, String> map = new HashMap<>();
// 獲取校驗(yàn)錯(cuò)誤結(jié)果
result.getFieldErrors().forEach((item) -> {
// 獲取錯(cuò)誤信息
String message = item.getDefaultMessage();
// 獲取字段名
String field = item.getField();
map.put(field, message);
});
return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMessage()).put("data", map);
}
@ExceptionHandler(value = Throwable.class)
public R handleException(Throwable throwable) {
log.error("出現(xiàn)問題{},異常類型{}", throwable.getMessage(), throwable.getClass());
return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
}
}