Spring MVC 全局异常处理器

如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。

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>

相关推荐

  1. 后端异常处理:全局异常处理器

    2024-03-09 22:28:07       47 阅读
  2. SpringMVC异常处理

    2024-03-09 22:28:07       65 阅读
  3. SpringMVC异常处理

    2024-03-09 22:28:07       39 阅读
  4. WPF 全局异常处理

    2024-03-09 22:28:07       60 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-09 22:28:07       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-09 22:28:07       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-09 22:28:07       82 阅读
  4. Python语言-面向对象

    2024-03-09 22:28:07       91 阅读

热门阅读

  1. CSS 工程结构

    2024-03-09 22:28:07       47 阅读
  2. Pytest教程:Pytest参数化测试

    2024-03-09 22:28:07       50 阅读
  3. SQL 中IN 列表的最佳使用情况

    2024-03-09 22:28:07       45 阅读
  4. 2402. 2-SAT 问题(tarjan,2-SAT模板题)

    2024-03-09 22:28:07       44 阅读
  5. STM32day3

    STM32day3

    2024-03-09 22:28:07      44 阅读
  6. 掌握mysql,看完这篇文章就够了

    2024-03-09 22:28:07       42 阅读
  7. Clickhouse & Elasticsearch 选型对比

    2024-03-09 22:28:07       42 阅读
  8. uniapp 小程序AP配网

    2024-03-09 22:28:07       41 阅读
  9. .Net Core/.Net 6/.Net 8 添加MIME类型

    2024-03-09 22:28:07       43 阅读
  10. c语言:求逆序后四位

    2024-03-09 22:28:07       34 阅读