spingmvc 异常处理[ 视频2笔记 ]
异常处理思路:
异常处理方法:
1. 自定义异常类CustomException.java
1 package com.itcast.ssm.exception; 2 3 /** 4 * 系统自定义异常类: 针对预期的异常, 需要在程序中抛出此类异常 5 */ 6 @SuppressWarnings("serial") 7 public class CustomException extends Exception { 8 9 // 异常信息 10 private String message; 11 12 public CustomException() { 13 super(); 14 } 15 16 public CustomException(String message) { 17 super(); 18 this.message = message; 19 } 20 21 public String getMessage() { 22 return message; 23 } 24 25 public void setMessage(String message) { 26 this.message = message; 27 } 28 }
2. 定义全局异常处理器
1 package com.itcast.ssm.exception; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import org.springframework.web.servlet.HandlerExceptionResolver; 7 import org.springframework.web.servlet.ModelAndView; 8 9 /** 10 * 全局异常处理器, 需要实现接口HandlerExceptionResolver, 只要实现了这个接口, 就是全局异常处理器 11 */ 12 public class CustomExceptionResolver implements HandlerExceptionResolver { 13 14 // handler就是处理器适配器要执行的Handler对象method 15 @Override 16 public ModelAndView resolveException(HttpServletRequest request, 17 HttpServletResponse response, Object handler, Exception ex) { 18 19 // 捕获异常 20 CustomException customException = null; 21 if (ex instanceof CustomException) { // 如果是自定义异常类 22 customException = (CustomException) ex; 23 } else { // 如果不是自定义异常类, 基本就是运行时异常 24 customException = new CustomException("未知错误"); 25 } 26 27 // 捕获异常信息 28 String message = customException.getMessage(); 29 30 // 将异常信息响应到页面 31 ModelAndView mv = new ModelAndView(); 32 mv.addObject("message", message); 33 mv.setViewName("error"); 34 35 return mv; 36 } 37 38 }
3. 创建错误页面error.jsp
1 <h3>${message }</h3>
4. 在springmvc.xml中配置全局异常处理器
1 <!-- 配置全局异常处理器 --> 2 <bean class="com.itcast.ssm.exception.CustomExceptionResolver"/>
测试:
(1) 如果是手动抛出的异常, 会在错误页面中显示自定义的异常信息
(2) 如果不是手动抛出的异常, 会在错误页面中显示"未知错误"的异常信息
--------------------------------------------------
1 // 商品信息修改页面的展示 2 @RequestMapping("/editItems") 3 public String editItems(Model model, Integer id) throws Exception { 4 // 根据id获取商品信息 5 ItemsCustom itemsCustom = itemsService.findItemsById(id); 6 7 // 判断商品是否为空, 根据id没有查询到商品, 抛出异常, 目的是提示用户商品信息不存在 8 if (itemsCustom == null) { 9 throw new CustomException("修改的商品信息不存在!"); 10 } 11 12 model.addAttribute("items", itemsCustom); 13 return "items/editItems"; 14 }
(1) 第一种异常类型测试: 在Handler中抛出异常
* 查询一个不存在的id, 制造异常
* 进入Handler对应方法, 捕获异常, 抛出CustomException预期类型异常
* 进入全局异常处理类CustomExceptionResolver, 进行异常判断, 如果是自定义类型异常
* 方法结束, 页面提示异常信息
(1) 第一张异常类型测试: 在service中抛出异常[先屏蔽掉Handler中的异常处理]