如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", ex.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount")
public String findAccount14(Model model) {
model.addAttribute("msg", "欢迎你 springmvc");
//模拟异常信息
int i = 10/0;
return "success";
}
}
<a href="/account/findAccount">异常处理器</a>