如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。
1.异常处理思路
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:

2.创建异常处理器
@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;
	}
}
3.测试
- 编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
   @RequestMapping("/findAccount14")
    public String findAccount14(Model model) {
        model.addAttribute("msg", "欢迎你 springmvc");
        //模拟异常信息
        int i = 10/0;
        return "success";
    }
}
- 在index.jsp里面定义超链接
<a href="/account/findAccount14">异常处理器</a>












![P8661 [蓝桥杯 2018 省 B] 日志统计](https://img-blog.csdnimg.cn/direct/81901ba6e7704740bc44601a41847668.png)






