package com.hy.utils;
import com.hy.common.exception.HyException;
import java.util.List;
import java.util.Map;
public class AssertUtils {
// 为空时抛异常 /
public static void isNotEmpty(Object value,String message){
if (null==value || "".equals(value)){
throw new HyException(message);
}
}
public static void isNotEmpty(Map<?, ?> map, String message) {
if (null==map || map.isEmpty()){
throw new HyException(message);
}
}
public static void isNotEmpty (Object[] array, String message) {
if (null==array || array.length == 0) {
throw new HyException(message);
}
}
public static void isNotEmpty (Integer value, String message) {
if (null==value || value== 0) {
throw new HyException(message);
}
}
public static void isNotEmpty (List<?> value, String message) {
if (null==value || value.size()== 0) {
throw new HyException(message);
}
}
// 不为空时抛异常 /
public static void isEmpty(List<?> value,String message){
if(null!=value && value.size()>0){
throw new HyException(message);
}
}
public static void isEmpty(Integer value,String message){
if(null!=value && value!=0){
throw new HyException(message);
}
}
public static void isEmpty (Object[] array, String message) {
if (null!=array && array.length != 0) {
throw new HyException(message);
}
}
public static void isEmpty(Object value,String message){
if (null!=value && !"".equals(value)){
throw new HyException(message);
}
}
public static void isEmpty(Map<?, ?> map, String message) {
if (null!=map && map.size()!=0){
throw new HyException(message);
}
}
}
其中HyException是自定义异常类
调用方法如下:
public static R checkValue(ActivityRequest act){
try{
AssertUtils.isNotEmpty(act.getResName(),"活动名称不能为空!");
AssertUtils.isNotEmpty(act.getResOwner(),"所属场馆不能为空!");
AssertUtils.isNotEmpty(act.getActivityType(),"活动分类不能为空!");
AssertUtils.isNotEmpty(act.getStartTime(),"开始时间不能为空!");
AssertUtils.isNotEmpty(act.getEndTime(),"结束时间不能为空!");
AssertUtils.isNotEmpty(act.getAddress(),"举办地点不能为空!");
AssertUtils.isNotEmpty(act.getLatitude(),"地址选择不能为空!");
AssertUtils.isNotEmpty(act.getLongitude(),"地址选择不能为空!");
AssertUtils.isNotEmpty(act.getStrPoster(),"资源海报不能为空!");
AssertUtils.isNotEmpty(act.getTotalNum(),"可订票数不能为空!");
AssertUtils.isNotEmpty(act.getSponsor(),"主办单位不能为空!");
AssertUtils.isNotEmpty(act.getContact(),"联系人不能为空!");
AssertUtils.isNotEmpty(act.getPhone(),"联系电话不能为空!");
AssertUtils.isNotEmpty(act.getActype(),"活动状态不能为空!");
AssertUtils.isNotEmpty(act.getDescription(),"活动详情不能为空!");
}catch (Exception e){
e.printStackTrace();
return R.error(e.getMessage());
}
return R.ok();
}
在controller类中捕获异常就行,return R.error(这里就是***不能为空的错误信息)