java项目中自定义业务异常

来源:互联网 发布:hr淘宝秒杀 编辑:程序博客网 时间:2024/05/22 11:36

在java  Web开发过程中会遇到各种的业务异常,如扣款余额不足,重复提交,重复秒杀等,我们在后台java代码中最好的方式是将这种通过异常的方式来捕获,然后逐级上抛,最终在页面上给出提示,在网上看到的一些代码贴出来供大家学习


1.定义异常类

package org.seckill.exception;/** * Created by zhangfx on 2017/7/7. */public class SeckillException extends RuntimeException {    public SeckillException(String message) {        super(message);    }    public SeckillException(String message, Throwable cause) {        super(message, cause);    }}

2.在接口的实现类中跑出异常

 @Override    @Transactional    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillCloseException {       if(md5==null||!md5.equals(getMD5(seckillId))){           throw new SeckillException("seckill data rewrite");       }        //执行秒杀逻辑        Date nowTime = new Date();        try{            //记录购买行为            int insertCount = successKilledDao.insertSuccessKilled(seckillId,userPhone);            if(insertCount<=0){                throw  new RepeatKillException("seckill repeated");            }else{                //减库存,热点商品竞争                int updateCount = seckillDao.reduceNumber(seckillId,nowTime);                if(updateCount<=0){                    //没有更新到秒杀记录,秒杀结束,rollback                    throw new SeckillCloseException("seckill data rewrite");                }else{                    //commit                    SuccessKilled successKilled=successKilledDao.queryByIdWithSeckill(seckillId,userPhone);                    return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS,successKilled);                }            }        }catch (SeckillCloseException e1){            throw e1;        }catch (RepeatKillException e2){            throw e2;        }catch (Exception e){            logger.error(e.getMessage(), e);            //所有编译异常转化为运行期异常            throw new SeckillException("seckill inner error:"+e.getMessage());        }    }

3.在controller中接到异常,转为相应的状态码,返回到前台

   @RequestMapping(value = "/{seckillId}/{md5}/execution",            method = RequestMethod.POST,            produces={"application/json;charset=UTF-8"})    @ResponseBody    public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Long seckillId,                                                   @PathVariable("md5")String md5,                                                   @CookieValue(value="killPhone",required = false) Long phone){        if(phone==null){            return new SeckillResult<SeckillExecution>(false,"未注册");        }        SeckillResult<SeckillExecution>  result;        try{            //调用代码执行秒杀            //SeckillExecution  execution= seckillService.executeSeckill(seckillId,phone,md5);            //调用存储过程执行秒杀            SeckillExecution  execution= seckillService.executeSeckillProcedure(seckillId,phone,md5);            return new SeckillResult<SeckillExecution>(true,execution);        }catch (RepeatKillException e){            SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.REPEAT_KILL);            return new SeckillResult<SeckillExecution>(true,execution);        }catch (SeckillCloseException e){            SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.END);            return new SeckillResult<SeckillExecution>(true,execution);        }catch(Exception e){            SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR);            return new SeckillResult<SeckillExecution>(true,execution);        }    }

4.界面上接到相应的异常状态码,然后做出相应的提示

 handleSeckillkill : function(seckillId,node){      //处理秒杀逻辑        node.hide()            .html("<button class='btn btn-primary btn-lg' id='killBtn'>开始秒杀</button>");        $.post(seckill.URL.exposer(seckillId),{},function(result){            //在回调函数中,执行交互            if(result && result['success']){                var exposer = result['data'];                if(exposer['exposed']){                    //开启秒杀                    //获取秒杀地址                    var md5 = exposer['md5'];                    var killUrl = seckill.URL.execution(seckillId,md5);                    console.log("killUrl:"+killUrl);                    //绑定一次点击事件                    $('#killBtn').one('click',function(){                        //绑定秒杀请求                        //1.先禁用按钮                        $(this).addClass('disabled');                        //2.发送秒杀请求                        $.post(killUrl,{},function(result){                            if(result && result['success']){                                var killResult = result['data'];                                var state = killResult['state'];                                var stateInfo = killResult['stateinfo'];                                //显示秒杀结果                                node.html('<span class="label label-success">'+stateInfo+'</span>');                            }                        });                    });                    node.show();                }else{                    //未开启秒杀                    var now = exposer['now'];                    var start = exposer['start'];                    var end = exposer['end'];                    //重新计算逻辑                    seckill.countdown(seckillId,now,start,end);                }            }else{                console.log('result'+result);            }        });    }