记录日志:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
private static Log log = LogFactory.getLog(AlarmDao.class);
自定义异常:
package com.h3c.itac.exception;
@SuppressWarnings("serial")
public class BaseException extends RuntimeException{
public BaseException(){super();}
public BaseException(String message){
super(message);
}
public BaseException(String message,Throwable throwable){
super(message, throwable);
}
public BaseException(Throwable throwable){
super(throwable);
}
}
dao层异常处理:
public void insertAlarm(Alarm alarm){
try{
// this.getHibernateTemplate().save(alarm);
int i=1/0;
log.info("插入一条告警信息...");
}catch(Exception e){
log.info("插入告警信息失败...",e);//自定义异常信息,可以记录到日志文件中,用于以后的错误修改参考,也可输出到控制台
e.printStackTrace();//输出错误信息到控制台,给程序员参考
throw new BaseException("插入告警失败...",e);//
}
}
service层异常:
@Transactional
public void insertUser(Alarm alarm) throws RuntimeException{
try{
this.alarmDao.insertAlarm(alarm);
}catch(BaseException e){//将dao层BaseException转换成RuntimeException
throw new RuntimeException(e.getMessage());
}
}
controller层异常:
@RequestMapping("saveAlarm")
public String onSaveAlarm(Alarm alarm,Map map){
System.out.println(alarm);
try {
this.alarmService.insertUser(alarm);
} catch (RuntimeException e) {
map.put("saveFlag", e.getMessage());
return "error";
}
return "alarm/addAlarm";
}