判断javabean是否非空,并给前台报出错误信息

1、工具类

package com.duodian.youhui.admin.utils;

import com.duodian.youhui.admin.Exceptions.AppException;
import com.duodian.youhui.entity.db.taobao.TaobaoWechat;

import java.lang.reflect.Field;

/**
 * 作者 :HealerJean
 * 日期 :2019/1/24  下午4:30.
 * 类描述:判断是否为空 或者是null 工具
 */
public class JudgeNullUtils {

    public static boolean isNull(Object object,String ... fieldName){
        try {
            for (int i = 0; i < fieldName.length; i++) {
                Field field = null;

                    field = object.getClass().getDeclaredField(fieldName[i]);

                field.setAccessible(true);//暴力反射,获取获取数据
                if(field.get(object)==null){
                    //返回flase或者直接抛出异常,根据我们的情况而定
                    throw  new AppException(fieldName[i]+"不能为空");
                }
            }
            return true ;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false ;
    }

}

2、catch捕获


    @ApiOperation(value = "添加淘宝营销总代理",
            notes = "添加淘宝营销总代理",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = ResponseBean.class
    )
    @ResponseBody
    @GetMapping("addEsWechat")
    public ResponseBean addEsWechat(TaobaoEsWechat taobaoWechat ){
        try {
            JudgeNullUtils.isNull(taobaoWechat,"code","status");
            return ResponseBean.buildSuccess(taobaoEsWechatService.addTaobaoEsWechat(taobaoWechat));
        } catch (AppException e) {
            ExceptionLogUtils.log(e, this.getClass());
            return ResponseBean.buildFailure(e.getCode(),e.getMessage());
        } catch (Exception e) {
            ExceptionLogUtils.log(e, this.getClass());
            return ResponseBean.buildFailure(e.getMessage());
        }
    }
posted @ 2019-01-24 16:46  HealerJean  阅读(118)  评论(0编辑  收藏  举报