前言
运行时异常的统一处理
自定义异常
public class ParamException extends RuntimeException {
public ParamException(String message) {
super(message);
}
}
自定义异常处理器
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@Autowired
Result r;
/** 处理参数异常 */
@ExceptionHandler(ParamException.class)
public Result handle(ParamException e) {
log.error(e.getMessage(), e);
return r.error(e.getMessage());
}
}
只要我们抛自定义的这个异常那么就会由这个处理方法来返回给前端信息
后端信息校验
我们用上面的技术可以实现后端校验的功能,比如pojo类需要前端传的字段如果没传我就抛异常让前端显示
public class House {
private int id;
@NotNull(message = "省份必填")
private Integer province;
private Integer city;
private Integer area;
@NotEmpty(message = "租住类型必填")
private String rentMode;
@NotEmpty(message = "户型必填")
private String houseType;
@NotEmpty(message = "朝向必填")
private String direction;
@NotNull(message = "租金必填")
@Range(min = 100,max = 10000)
private Double rental;
@NotEmpty(message = "房屋照片必填")
private String pic;
private String areaName;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateTime;
private String address;
private int rentalType;
}
然后我们来一个处理器
public class ValidationUtil {
private static final Validator validator;
static {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
public static void validate(Object object) {
Set<ConstraintViolation<Object>> violations = validator.validate(object);
if(CollectionUtils.isNotEmpty(violations)) {
StringBuffer msgBuf = new StringBuffer();
violations.forEach(violation -> {
String message = violation.getMessage();
msgBuf.append(message).append(";");
});
throw new ParamException(msgBuf.toString());
}
}
}
Controller就可以这么搞
@PostMapping('/house')
public Result addHouse(@RequestBody House house){
ValidationUtil.validate(house);//负责抛异常,没问题再去麻烦服务层
service.addHouse(house);
return r.success("");
}