springmvc-学习总结-全局异常处理

来源:互联网 发布:新东方游学数据 编辑:程序博客网 时间:2024/05/18 01:51

先来个自定义异常

public class CustomException extends Exception {//异常信息public String message;public CustomException(String message){super(message);this.message=message;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}

定义全局异常处理类需要实现HandlerExceptionResolver接口:


public class CustomExceptionResolve implements HandlerExceptionResolver {public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) {CustomException customException=null;if(ex instanceof CustomException){customException = (CustomException)ex;}else{customException=new CustomException("未知错误");}ModelAndView mv = new ModelAndView("error");mv.addObject("error", customException.getMessage());return mv;}}

写一个显示异常信息的页面然后就是springmvc配置文件中声明一下全局异常处理类:



最后就是测试了:


@RequestMapping("testException1")public void testException1() throws CustomException{try {int i =1/0;} catch (Exception e) {throw new CustomException("程序出现问题了");}}@RequestMapping("testException2")public void testException2(){int i =1/0;}

结果如下:



原创粉丝点击