示例代码
@RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView addEmployee(Model model, EmpTO empTO, BindingResult bindingResult){
try {
empService.saveOrUpdateEmployee(empTO);
} catch (Exception e) {
if (e instanceof InvException) {
model.addAttribute("error", ((InvException) e).getError());
} else {
model.addAttribute("error", PresentationUtil.handleApplicationRuntimeError(e));
}
return new ModelAndView("emp/save");
}
empTO = new EmpTO();
return new ModelAndView("emp/home");
}
Thank.s
答案 0 :(得分:0)
我们使用@ExceptionHandler
注释,它允许我们处理Controller方法之外的异常。无需将错误代码放在数据库表中。
异常类:
public class InvException extends RuntimeException {
private String errorCode;
private String errorMsg;
//setter/getter
...
}
并在控制器中
@RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView addEmployee(Model model, EmpTO empTO, BindingResult bindingResult){
...
} catch (InvException e) {
throw new InvException("E400", "This is Inv Exception");
} catch (Exception e) {
throw new Exception(...);
}
}
@ExceptionHandler(InvException.class)
public ModelAndView handleMyOwnException(InvException ex) {
ModelAndView model = new ModelAndView("your specific error view");
model.addObject("errCode", ex.getErrorCode());
model.addObject("errMsg", ex.getErrorMsg());
return model;
}
@ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception ex) {
ModelAndView model = new ModelAndView("your generic error view ");
model.addObject("errMsg", "There is a exception");
return model;
}
此@ExceptionHandler
适用于单个控制器。它可以通过创建一个新类并使用@ControllerAdvice
@ControllerAdvice
public class GlobalExceptionController {
@ExceptionHandler(InvException.class)
public ModelAndView handleMyOwnException(InvException ex) {...}
@ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception ex) {...}
}