SpringMVC学习--异常处理器

  • 简介

  springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。

  • 异常处理思路

  系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。

  系统的daoservicecontroller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:

  • 自定义异常类

  为了区别不同的异常通常根据异常类型自定义异常类,这里我们创建一个自定义系统异常,如果controllerservicedao抛出此类异常说明是系统预期处理的异常信息。

 1 public class CustomException extends Exception {
 2 
 3     /** serialVersionUID*/
 4     private static final long serialVersionUID = -5212079010855161498L;
 5     
 6     public CustomException(String message){
 7         super(message);
 8         this.message = message;
 9     }
10 
11     //异常信息
12     private String message;
13 
14     public String getMessage() {
15         return message;
16     }
17 
18     public void setMessage(String message) {
19         this.message = message;
20     }
21 }
  • 自定义的异常处理器
 1 public class CustomExceptionResolver implements HandlerExceptionResolver {
 2 
 3     @Override
 4     public ModelAndView resolveException(HttpServletRequest request,
 5             HttpServletResponse response, Object handler, Exception ex) {
 6 
 7         ex.printStackTrace();
 8 
 9         CustomException customException = null;
10         
11         //如果抛出的是系统自定义异常则直接转换
12         if(ex instanceof CustomException){
13             customException = (CustomException)ex;
14         }else{
15             //如果抛出的不是系统自定义异常则重新构造一个未知错误异常。
16             customException = new CustomException("未知错误,请与系统管理 员联系!");
17         }
18         
19         ModelAndView modelAndView = new ModelAndView();
20         modelAndView.addObject("message", customException.getMessage());
21         modelAndView.setViewName("error");
22 
23         return modelAndView;
24     }
25 
26 }
  • 错误页面 
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 4 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%> 
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9 <title>错误页面</title>
10 
11 </head>
12 <body>
13 您的操作出现错误如下:<br/>
14 ${message }
15 </body>
16 
17 </html>
  • 异常处理器配置

  springmvc.xml中添加:

1 <!-- 异常处理器 -->
2     <bean id="handlerExceptionResolver" class="com.luchao.controller.exceptionResolver.CustomExceptionResolver"/>

 

 

 

原文地址:https://www.cnblogs.com/lcngu/p/5517933.html