我在Controller类中有以下代码,出于某种原因,尽管我实现了异常处理以及try.....catch块,但我仍然无法捕获我的异常。
我只是在执行一个测试,在DAO类中,我更改了插入数据库的 sql 字符串以省略一列,这样DAO就会失败。DAO类失败并且错误被写入日志,但是即使officerManager.RegisterOfficer(officer)不成功,代码也会继续返回model.addAttribute("results","Record Was Saved")。
这不准确,我希望控制器抛出错误。下面是代码。
控制器
@RequestMapping(value="officer_registration.htm", method=RequestMethod.POST)
public ModelAndView handleRequest(@Valid @ModelAttribute Officers officer,BindingResult result,ModelMap m,Model model,HttpServletRequest request,HttpServletResponse response)throws Exception{
try{
if(result.hasErrors()){
model.addAttribute("division", myDivision);
model.addAttribute("position", myPosition);
model.addAttribute("gender", myGender);
return new ModelAndView("officer_registration");
}else{
//check the request if its an update or an insert
String user_request = request.getParameter("user_request");
logger.info("The Users Request Was " + user_request);
if (user_request.equals("Save")){
officerManager.RegisterOfficer(officer);
model.addAttribute("results","Record Was Saved");
}else{
officerManager.UpdateOfficer(officer);
model.addAttribute("results","Record Was Updated");
}
model.addAttribute("division", myDivision);
model.addAttribute("position", myPosition);
model.addAttribute("gender", myGender);
return new ModelAndView("officer_registration");
}
}catch(Exception e ){
model.addAttribute("division", myDivision);
model.addAttribute("position", myPosition);
model.addAttribute("gender", myGender);
model.addAttribute("results","Error: Unable to Save Record!");
return new ModelAndView("officer_registration");
}
}
道
public void saveOfficer(Officers officer) {
logger.info("In saveOfficer");
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try{
int count = getJdbcTemplate().update("INSERT INTO crimetrack.tblofficers (userName,password, fName, lName, oName, divisionNo, positionId, emailAdd, startDate, endDate, genderId,phoneNo, dob,badgeNo) "+
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
, new Object[]{officer.getUserName(),StringSecurity.EncryptString(officer.getPassword()),officer.getfName(),
officer.getlName(),officer.getoName(),officer.getDivisionNo(),officer.getPositionId(),
officer.getEmailAdd(),officer.getStartDate(),officer.getEndDate(),officer.getGenderId(),
officer.getPhoneNo(),officer.getDob(),officer.getBadgeNo()});
logger.info(count +" Rows affected in tblOfficers");
}catch(Exception e){
logger.error("Could not save officer ", e);
}
}