最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Springmvc自定义异常处理器实现代码流程解析
时间:2020-07-07 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Springmvc自定义异常处理器实现代码流程解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
当dispatchServlet接收到controller抛出的异常时,会将异常交由 HandlerExceptionResolver
异常处理器处理!我们可以创建自定义异常处理器实现该接口来处理自定义异常
1) 自定义异常类
public class MyException extends Exception { // 异常信息 private String message; public MyException() { super(); } public MyException(String message) { super(); this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2)自定义异常处理器
public class CustomHandleException implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { // 定义异常信息 String msg; // 判断异常类型 if (exception instanceof MyException) { // 如果是自定义异常,读取异常信息 msg = exception.getMessage(); } else { // 如果是运行时异常,则取错误堆栈,从堆栈中获取异常信息 Writer out = new StringWriter(); PrintWriter s = new PrintWriter(out); exception.printStackTrace(s); msg = out.toString(); } // 把错误信息发给相关人员,邮件,短信等方式 // TODO // 返回错误页面,给用户友好页面显示错误信息 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("msg", msg); modelAndView.setViewName("error"); return modelAndView; } }
3)在springmvc.xml中配置异常处理器
4)定制错误页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>Insert title here 系统发生异常了!
异常信息
${msg }
5)测试异常处理
@RequestMapping(value = "/item/itemlist.action") public ModelAndView itemList() throws MyException{ Listlist = itemService.selectItemsList(); if(true){ throw new MyException("商品列表不能为空!!"); } ModelAndView mav = new ModelAndView(); mav.addObject("itemList", list); mav.setViewName("itemList"); return mav; }
相关文章
- SpringBoot自定义bean绑定解析 10-24
- Javaweb工程运行报错HTTP Status 404解决教程 10-20
- JAVA获取jvm和操作系统相关信息方法 10-20
- BeanFactory和FactoryBean的区别讲解 10-20
- 微信小程序的宿主环境实现教程 10-10
- dispatchEvent解决重叠元素响应事件教程 10-10