1、添加HttpStatus的依赖包
org.apache.httpcomponents
httpcore
4.4.15
compile
2、添加校验依赖包
org.springframework.boot
spring-boot-starter-validation
2.7.2
3、定义一个统一的返回结果类R
package com.xu.common.utils;
import org.apache.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
/**
* 返回数据
*/
public class R extends HashMap {
private static final long serialVersionUID = 1L;
public R() {
put("code", 0);
put("msg", "success");
}
public static R error() {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
}
public static R error(String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
public static R error(int code, String msg) {
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(String msg) {
R r = new R();
r.put("msg", msg);
return r;
}
public static R ok(Map map) {
R r = new R();
r.putAll(map);
return r;
}
public static R ok() {
return new R();
}
public R put(String key, Object value) {
super.put(key, value);
return this;
}
}
4、枚举异常状态码
public enum ErrorCodeEnume {
UNKNOW_EXCEPTION(10000,"系统未知异常"),
VAILD_EXCEPTION(10001,"参数格式校验失败");
private int code;
private String msg;
BizCodeEnume(int code,String msg){
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
5、在需要校验的实体类的属性上添加注解
@NotBlank(message = "用户名不能为空")
private String name;
6.1、在controller中添加 @valid注解与BindingResult
@RequestMapping("/save")
public R save(@Valid @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
Map map = new HashMap<>();
result.getFieldErrors().forEach((item)->{
String message = item.getDefaultMessage();
String field = item.getField();
map.put(field,message);
});
return R.error(ErrorCodeEnume.VAILD_EXCEPTION.getCode(), ErrorCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
}
else
{
UserService.save(user);
}
return R.ok();
}
6.2或者利用RestControllerAdvice注解将异常统一抛出(这个注解利用AOP原理)
import com.xu.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 = "需要检测异常的包名,一般为controller包")
public class ExceptionController {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleVaildException(MethodArgumentNotValidException e){
Map map = new HashMap<>();
BindingResult result = e.getBindingResult();
result.getFieldErrors().forEach((item)->{
String message = item.getDefaultMessage();
String field = item.getField();
map.put(field,message);
});
log.error("数据校验出现问题{}",map);
return R.error(ErrorCodeEnume.VAILD_EXCEPTION.getCode(), ErrorCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
}
}
@ExceptionHandler(value = Throwable.class)
public R handleException(Throwable throwable)
{
return R.error(ErrorCodeEnume.UNKNOW_EXCEPTION.getCode(), ErrorCodeEnume.UNKNOW_EXCEPTION.getMsg());
}
7、通过postman测试返回结果
"msg": "提交的数据不合法",
"code": 400,
"data": {
"name": "用户名不能为空"
}