一个包装异常的小例子.
1.因为BeanUtils本身就会需要抛出异常,但所有的异常都是Exception
2.这个例子,需求是更新一个拼单,这里使用到了助手类(临时发现,如果是Date类型为空则会出现异常,使用需注意),在更新完拼单后将这个拼单返回,并告知更新成功或者失败.
下面是这个异常包装类
继承RuntimeException,重写了构造方法
测试类
public Activity updateActivity(Map Mapactivity) {
Long id = Long.valueOf(Mapactivity.get("id").toString());
Activity act = (Activity)this.getHibernateTemplate().get(Activity.class,id);
try {
BeanUtils.populate(act,Mapactivity);
this.getHibernateTemplate().update(act);
}catch(Exception e){
throw new DolphinOperationException(e,CodeCategories.UPDATE_FAILURE); //CodeCategories.UPDATE_FAILURE 常量200或者400
}
return act;
}
1.因为BeanUtils本身就会需要抛出异常,但所有的异常都是Exception
2.这个例子,需求是更新一个拼单,这里使用到了助手类(临时发现,如果是Date类型为空则会出现异常,使用需注意),在更新完拼单后将这个拼单返回,并告知更新成功或者失败.
下面是这个异常包装类
public class DolphinOperationException extends RuntimeException {
private Integer errorCode; //定义一个错误编码
public DolphinOperationException(Integer errorCode) {
this.errorCode = errorCode;
}
public DolphinOperationException(Throwable cause, Integer errorCode) {
super(cause);
this.errorCode = errorCode;
}
public DolphinOperationException(Integer errorCode,String message) {
super(message);
}
public DolphinOperationException(String message, Throwable cause, Integer errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
public Integer getErrorCode() {
return errorCode;
}
}
继承RuntimeException,重写了构造方法
测试类
@Test
@Rollback(false)
public void updateActivity(){
Address ads = new Address();
ads.setAddress("22222");
User user = new User();
user.setId(15l);
Activity act = new Activity();
act.setId(2l);
act.setAddress(ads);
act.setStartTime(new Date());
act.setTitle("光棍节写测试1");
Activity activity=am.updateActivity(act);
assertNotNull(activity);
}