-
定义自定义异常类
public class CustomException extends Exception { private String message; public CustomException(String message) { this.message = message; } public String getMessage() { return message; } }
-
定义异常处理器
public class CustomHandlerExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) { //1.处理异常 CustomException customException = null; //已知错误 if(ex instanceof CustomException) { customException = (CustomException)ex; } //未知错误 else { customException = new CustomException("未知错误"+ex.getMessage()); } //记录日志或发送邮件给管理 员,降低耦合度 //log(); //sendEmail(); //2.异常处理完成之后,跳转指定页面,并且显示错误信息 ModelAndView mav = new ModelAndView(); mav.addObject("exceptionMessage", customException.getMessage()); mav.setViewName("WEB-INF/exception");// /WEB-INF/exception.jsp return mav; }
}
-
在spring-mvc.xml中配置异常处理器
<!-- 配置全局异常处理器 --> <bean class="com.neuedu.exception.CustomHandlerExceptionResolver"></bean>
-
编写异常信息文件UserController、UserService、UserDao,并在UserDao的方法中抛出自定义异常
public boolean selectUser(String username,String password) throws CustomException { System.out.println("UserDao: " + username + " " + password); try { //制造异常(检查性异常、预期异常、非运行时异常) FileInputStream input = new FileInputStream(new File("file.txt")); } catch (FileNotFoundException e) { //记录日志或发送邮件给管理 ,耦合度太高,所有的catch都需要修改,所以抛出异常,去全局异常处理器进行处理 //log(); //sendEmail(); throw new CustomException("UserDao.selectUser("+username+"," + password + "):file.txt文件找不到"); } return true; }
-
测试
http://localhost:8088/springMVC_06_exception/login.action?username=marry&password=111111
SpringMVC 异常处理配置
最新推荐文章于 2025-03-26 14:15:35 发布