使用Spring MVC统一异常处理实战

简介: 使用Spring MVC统一异常处理实战 博客分类:  J2EE Spring Spring MVC 案例文档SpringMVC异常处理  1 描述  在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。
1 描述 
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。 
那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring MVC统一处理异常的解决和实现过程。 

2 分析 
Spring MVC处理异常有3种方式: 
(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver; 
(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器; 
(3)使用@ExceptionHandler注解实现异常处理; 

3 实战 
3.1 引言 
为了验证Spring MVC的3种异常处理方式的实际效果,我们需要开发一个测试项目,从Dao层、Service层、Controller层分别抛出不同的异常,然后分别集成3种方式进行异常处理,从而比较3种方式的优缺点。 

3.2 实战项目 
3.2.1 项目结构 
 

3.2.2 Dao层代码 
Java代码   收藏代码
  1. @Repository("testDao")  
  2. public class TestDao {  
  3.     public void exception(Integer id) throws Exception {  
  4.         switch(id) {  
  5.         case 1:  
  6.             throw new BusinessException("12""dao12");  
  7.         case 2:  
  8.             throw new BusinessException("22""dao22");  
  9.         case 3:  
  10.             throw new BusinessException("32""dao32");  
  11.         case 4:  
  12.             throw new BusinessException("42""dao42");  
  13.         case 5:  
  14.             throw new BusinessException("52""dao52");  
  15.         default:  
  16.             throw new ParameterException("Dao Parameter Error");  
  17.         }  
  18.     }  
  19. }  

3.2.3 Service层代码 
Java代码   收藏代码
  1. public interface TestService {  
  2.     public void exception(Integer id) throws Exception;  
  3.       
  4.     public void dao(Integer id) throws Exception;  
  5. }  
  6.   
  7. @Service("testService")  
  8. public class TestServiceImpl implements TestService {  
  9.     @Resource  
  10.     private TestDao testDao;  
  11.       
  12.     public void exception(Integer id) throws Exception {  
  13.         switch(id) {  
  14.         case 1:  
  15.             throw new BusinessException("11""service11");  
  16.         case 2:  
  17.             throw new BusinessException("21""service21");  
  18.         case 3:  
  19.             throw new BusinessException("31""service31");  
  20.         case 4:  
  21.             throw new BusinessException("41""service41");  
  22.         case 5:  
  23.             throw new BusinessException("51""service51");  
  24.         default:  
  25.             throw new ParameterException("Service Parameter Error");  
  26.         }  
  27.     }  
  28.   
  29.     @Override  
  30.     public void dao(Integer id) throws Exception {  
  31.         testDao.exception(id);  
  32.     }  
  33. }  

3.2.4 Controller层代码 
Java代码   收藏代码
  1. @Controller  
  2. public class TestController {  
  3.     @Resource  
  4.     private TestService testService;  
  5.       
  6.     @RequestMapping(value = "/controller.do", method = RequestMethod.GET)  
  7.     public void controller(HttpServletResponse response, Integer id) throws Exception {  
  8.         switch(id) {  
  9.         case 1:  
  10.             throw new BusinessException("10""controller10");  
  11.         case 2:  
  12.             throw new BusinessException("20""controller20");  
  13.         case 3:  
  14.             throw new BusinessException("30""controller30");  
  15.         case 4:  
  16.             throw new BusinessException("40""controller40");  
  17.         case 5:  
  18.             throw new BusinessException("50""controller50");  
  19.         default:  
  20.             throw new ParameterException("Controller Parameter Error");  
  21.         }  
  22.     }  
  23.       
  24.     @RequestMapping(value = "/service.do", method = RequestMethod.GET)  
  25.     public void service(HttpServletResponse response, Integer id) throws Exception {  
  26.         testService.exception(id);  
  27.     }  
  28.       
  29.     @RequestMapping(value = "/dao.do", method = RequestMethod.GET)  
  30.     public void dao(HttpServletResponse response, Integer id) throws Exception {  
  31.         testService.dao(id);  
  32.     }  
  33. }  

3.2.5 JSP页面代码 
Java代码   收藏代码
  1. <%@ page contentType="text/html; charset=UTF-8"%>  
  2. <html>  
  3. <head>  
  4. <title>Maven Demo</title>  
  5. </head>  
  6. <body>  
  7. <h1>所有的演示例子</h1>  
  8. <h3>[url=./dao.do?id=1]Dao正常错误[/url]</h3>  
  9. <h3>[url=./dao.do?id=10]Dao参数错误[/url]</h3>  
  10. <h3>[url=./dao.do?id=]Dao未知错误[/url]</h3>  
  11.   
  12.   
  13. <h3>[url=./service.do?id=1]Service正常错误[/url]</h3>  
  14. <h3>[url=./service.do?id=10]Service参数错误[/url]</h3>  
  15. <h3>[url=./service.do?id=]Service未知错误[/url]</h3>  
  16.   
  17.   
  18. <h3>[url=./controller.do?id=1]Controller正常错误[/url]</h3>  
  19. <h3>[url=./controller.do?id=10]Controller参数错误[/url]</h3>  
  20. <h3>[url=./controller.do?id=]Controller未知错误[/url]</h3>  
  21.   
  22.   
  23. <h3>[url=./404.do?id=1]404错误[/url]</h3>  
  24. </body>  
  25. </html>  

3.3 集成异常处理 
3.3.1 使用SimpleMappingExceptionResolver实现异常处理 
1、在Spring的配置文件applicationContext.xml中增加以下内容: 
Xml代码   收藏代码
  1. <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  2.     <!-- 定义默认的异常处理页面,当该异常类型的注册时使用 -->  
  3.     <property name="defaultErrorView" value="error"></property>  
  4.     <!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->  
  5.     <property name="exceptionAttribute" value="ex"></property>  
  6.     <!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常也页名作为值 -->  
  7.     <property name="exceptionMappings">  
  8.         <props>  
  9.             <prop key="cn.basttg.core.exception.BusinessException">error-business</prop>  
  10.             <prop key="cn.basttg.core.exception.ParameterException">error-parameter</prop>  
  11.   
  12.             <!-- 这里还可以继续扩展对不同异常类型的处理 -->  
  13.         </props>  
  14.     </property>  
  15. </bean>  

2、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。 

3、从上面的集成过程可知,使用SimpleMappingExceptionResolver进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,但该方法仅能获取到异常信息,若在出现异常时,对需要获取除异常以外的数据的情况不适用。 

3.3.2 实现HandlerExceptionResolver 接口自定义异常处理器 
1、增加HandlerExceptionResolver 接口的实现类MyExceptionHandler,代码如下: 
Java代码   收藏代码
  1. public class MyExceptionHandler implements HandlerExceptionResolver {  
  2.   
  3.     public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,  
  4.             Exception ex) {  
  5.         Map<String, Object> model = new HashMap<String, Object>();  
  6.         model.put("ex", ex);  
  7.           
  8.         // 根据不同错误转向不同页面  
  9.         if(ex instanceof BusinessException) {  
  10.             return new ModelAndView("error-business", model);  
  11.         }else if(ex instanceof ParameterException) {  
  12.             return new ModelAndView("error-parameter", model);  
  13.         } else {  
  14.             return new ModelAndView("error", model);  
  15.         }  
  16.     }  
  17. }  

2、在Spring的配置文件applicationContext.xml中增加以下内容: 
Xml代码   收藏代码
  1. <bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>  

3、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。 

4、从上面的集成过程可知,使用实现HandlerExceptionResolver接口的异常处理器进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,同时,在异常处理时能获取导致出现异常的对象,有利于提供更详细的异常处理信息。 

3.3.3 使用@ExceptionHandler注解实现异常处理 
1、增加BaseController类,并在类中使用@ExceptionHandler注解声明异常处理,代码如下: 
Java代码   收藏代码
  1. public class BaseController {  
  2.     /** 基于@ExceptionHandler异常处理 */  
  3.     @ExceptionHandler  
  4.     public String exp(HttpServletRequest request, Exception ex) {  
  5.           
  6.         request.setAttribute("ex", ex);  
  7.           
  8.         // 根据不同错误转向不同页面  
  9.         if(ex instanceof BusinessException) {  
  10.             return "error-business";  
  11.         }else if(ex instanceof ParameterException) {  
  12.             return "error-parameter";  
  13.         } else {  
  14.             return "error";  
  15.         }  
  16.     }  
  17. }  

2、修改代码,使所有需要异常处理的Controller都继承该类,如下所示,修改后的TestController类继承于BaseController: 
Java代码   收藏代码
  1. public class TestController extends BaseController  

3、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。 

4、从上面的集成过程可知,使用@ExceptionHandler注解实现异常处理,具有集成简单、有扩展性好(只需要将要异常处理的Controller类继承于BaseController即可)、不需要附加Spring配置等优点,但该方法对已有代码存在入侵性(需要修改已有代码,使相关类继承于BaseController),在异常处理时不能获取除异常以外的数据。 

3.4 未捕获异常的处理 
对于Unchecked Exception而言,由于代码不强制捕获,往往被忽略,如果运行期产生了Unchecked Exception,而代码中又没有进行相应的捕获和处理,则我们可能不得不面对尴尬的404、500……等服务器内部错误提示页面。 
我们需要一个全面而有效的异常处理机制。目前大多数服务器也都支持在Web.xml中通过<error-page>(Websphere/Weblogic)或者<error-code>(Tomcat)节点配置特定异常情况的显示页面。修改web.xml文件,增加以下内容: 
Xml代码   收藏代码
  1. <!-- 出错页面定义 -->  
  2. <error-page>  
  3.     <exception-type>java.lang.Throwable</exception-type>  
  4.     <location>/500.jsp</location>  
  5. </error-page>  
  6. <error-page>  
  7.     <error-code>500</error-code>  
  8.     <location>/500.jsp</location>  
  9. </error-page>  
  10. <error-page>  
  11.     <error-code>404</error-code>  
  12.     <location>/404.jsp</location>  
  13. </error-page>  
  14.   
  15. <!-- 这里可继续增加服务器错误号的处理及对应显示的页面 -->  

4 解决结果 
1、运行测试项目显示的首页,如下图所示: 


2、业务错误显示的页面,如下图所示: 


3、参数错误显示的页面,如下图所示: 


4、未知错误显示的页面,如下图所示: 


5、服务器内部错误页面,如下图所示: 


5 总结 
综合上述可知,Spring MVC集成异常处理3种方式都可以达到统一异常处理的目标。从3种方式的优缺点比较,若只需要简单的集成异常处理,推荐使用SimpleMappingExceptionResolver即可;若需要集成的异常处理能够更具个性化,提供给用户更详细的异常信息,推荐自定义实现HandlerExceptionResolver接口的方式;若不喜欢Spring配置文件或要实现“零配置”,且能接受对原有代码的适当入侵,则建议使用@ExceptionHandler注解方式。 

6 源代码 
源代码项目如下所示,为Maven项目,若需运行,请自行获取相关的依赖包。 
点击这里获取源代码 

7 参考资料 
[1] Spring MVC统一处理异常的方法 
http://hi.baidu.com/99999999hao/blog/item/25da70174bfbf642f919b8c3.html 
[2] SpringMVC 异常处理初探 
http://exceptioneye.iteye.com/blog/1306150 
[3] Spring3 MVC 深入研究 
http://elf8848.iteye.com/blog/875830 
[4] Spring MVC异常处理 
http://blog.csdn.net/rj042/article/details/7380442
分享到:   
评论
20 楼  join_lin 2014-04-08    引用
LZ写得不错,有用。
19 楼  jzhx107 2014-03-17    引用
   不错,谢谢!
18 楼  gary_bu 2014-03-05    引用
很专业,学习了
17 楼  yjlleilei 2014-02-19    引用
真是专业!
16 楼  cgs1999 2013-12-23    引用
qingbo921 写道
你好,楼主,最近我在某某框架上看到一种特殊的效果:

当用户请求某个页面操作按钮,只要执行失败,不进行页面跳转的情况下,统一抛出异常并

alert出来!目前我也想这么搞,能否给点思路呢???


这个是采用ajax来实现的,推荐使用jquery,参考代码:

Java代码   收藏代码
  1. @Controller    
  2. public class TestController {    
  3.     @RequestMapping(value = "/ajax.do")  
  4.     public void ajax(HttpServletResponse response, User user) throws Exception {  
  5.         if(user.getId()==null) {  
  6.             if(user.getUserName()==null || "".equals(user.getUserName())) {  
  7.                 AjaxUtils.rendJson(response, false"用户名为空创建失败");  
  8.             } else {  
  9.                 AjaxUtils.rendJson(response, true"创建用户成功");  
  10.             }  
  11.         } else {  
  12.             AjaxUtils.rendJson(response, true"修改用户成功");  
  13.         }  
  14.     }  
  15.         ...  
  16. }  


Html代码   收藏代码
  1. <!DOCTYPE html>  
  2. <html>  
  3.  <head>  
  4.   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">   
  5.   <title>AJAX请求</title>  
  6.   <script type="text/javascript" src="./jquery-1.10.2.min.js"></script>  
  7.   <script type="text/javascript">  
  8.   $(function(){  
  9.         init();  
  10.     });  
  11.     
  12.   function init(){  
  13.   
  14.         $("#ajaxCreate").click(function(){  
  15.             doAjax({userName: "cgs1999", realName: "cgs"});  
  16.         })  
  17.   
  18.         $("#ajaxUpdate").click(function(){  
  19.             doAjax({id: 1, userName: "cgs1999", realName: "cgs"});  
  20.         })  
  21.   
  22.         $("#ajaxFail").click(function(){  
  23.             doAjax({realName: "cgs"});  
  24.         })  
  25.           
  26.     }  
  27.   function doAjax(data) {  
  28.       $.post("./ajax.do",data,function(t){  
  29.             if(!t.success){  
  30.                 alert("操作失败, 原因:" + t.message);  
  31.             }else{  
  32.                 alert("操作成功, 描述:" + t.message);  
  33.             }  
  34.         },"json").error(function(){  
  35.             alert("未知错误");  
  36.         });  
  37.   }  
  38.   </script>  
  39.  </head>  
  40. <body>  
  41.   <br />  
  42.   <a id="ajaxCreate" href="#">创建用户成功</a>  
  43.     
  44.   <br />  
  45.   <a id="ajaxUpdate" href="#">修改用户成功</a>  
  46.     
  47.   <br />  
  48.   <a id="ajaxFail" href="#">用户名为空创建失败</a>  
  49. </body>  
  50. </html>  

15 楼  qingbo921 2013-12-20    引用
你好,楼主,最近我在某某框架上看到一种特殊的效果:

当用户请求某个页面操作按钮,只要执行失败,不进行页面跳转的情况下,统一抛出异常并

alert出来!目前我也想这么搞,能否给点思路呢???
14 楼  cgs1999 2013-10-22    引用
weipeng1986 写道
貌似如果是ajax请求的话,异常不会捕捉到,求解


看了一下之前的代码,controllerAjax方法定义有问题,不应该抛出异常,即将下面代码中的throws Exception去掉试试

之前提供的代码
------------------------------------------------
Java代码   收藏代码
  1. @Controller    
  2. public class TestController {    
  3.     @Resource    
  4.     private TestService testService;    
  5.         
  6.     @RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)    
  7.     public void controllerAjax(HttpServletResponse response, Integer id) throws Exception {    
  8.         try {    
  9.             testService.dao(id);    
  10.             AjaxUtils.rendJson(response, true"操作成功");    
  11.         } catch(Exception be) {    
  12.             AjaxUtils.rendJson(response, false"操作失败");    
  13.         }    
  14.     }    
  15.     ……    
  16. }  


修改后的代码
------------------------------------------------
Java代码   收藏代码
  1. @Controller    
  2. public class TestController {    
  3.     @Resource    
  4.     private TestService testService;    
  5.         
  6.     @RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)    
  7.     public void controllerAjax(HttpServletResponse response, Integer id) {    
  8.         try {    
  9.             testService.dao(id);    
  10.             AjaxUtils.rendJson(response, true"操作成功");    
  11.         } catch(Exception be) {    
  12.             AjaxUtils.rendJson(response, false"操作失败");    
  13.         }    
  14.     }    
  15.     ……    
  16. }  
13 楼  weipeng1986 2013-10-22    引用
貌似如果是ajax请求的话,异常不会捕捉到,求解
12 楼  weipeng1986 2013-10-22    引用
 很清晰明了
11 楼  cgs1999 2013-08-04    引用
snailxr 写道
楼主,controller里里面有的方法是返回到页面,但是有的方法如果存在异常的话需要通过json返回异信息,这个有木有好的解决方案


可以通过在controller中捕获相关的Exception,将相关的异常封装为JSON继续抛出

Java代码   收藏代码
  1. /** 
  2.  * 系统业务异常 
  3.  */  
  4. public class BusinessException extends RuntimeException {  
  5.   
  6.     /** serialVersionUID */  
  7.     private static final long serialVersionUID = 2332608236621015980L;  
  8.   
  9.     private String code;  
  10.   
  11.     public BusinessException() {  
  12.         super();  
  13.     }  
  14.   
  15.     public BusinessException(String message) {  
  16.         super(message);  
  17.     }  
  18.   
  19.     public BusinessException(String code, String message) {  
  20.         super(message);  
  21.         this.code = code;  
  22.     }  
  23.   
  24.     public BusinessException(Throwable cause) {  
  25.         super(cause);  
  26.     }  
  27.   
  28.     public BusinessException(String message, Throwable cause) {  
  29.         super(message, cause);  
  30.     }  
  31.   
  32.     public BusinessException(String code, String message, Throwable cause) {  
  33.         super(message, cause);  
  34.         this.code = code;  
  35.     }  
  36.   
  37.     public String getCode() {  
  38.         return code;  
  39.     }  
  40.   
  41.     public void setCode(String code) {  
  42.         this.code = code;  
  43.     }  
  44.   
  45. }  
  46.   
  47.   
  48. public class ParameterException extends RuntimeException {  
  49.   
  50.     /** serialVersionUID */  
  51.     private static final long serialVersionUID = 6417641452178955756L;  
  52.   
  53.     public ParameterException() {  
  54.         super();  
  55.     }  
  56.   
  57.     public ParameterException(String message) {  
  58.         super(message);  
  59.     }  
  60.   
  61.     public ParameterException(Throwable cause) {  
  62.         super(cause);  
  63.     }  
  64.   
  65.     public ParameterException(String message, Throwable cause) {  
  66.         super(message, cause);  
  67.     }  
  68. }  
  69.   
  70.   
  71. @Controller  
  72. public class TestController {  
  73.     @Resource  
  74.     private TestService testService;  
  75.       
  76.     @RequestMapping(value = "/controllerJson.do", method = RequestMethod.GET)  
  77.     public void controllerJson(HttpServletResponse response, Integer id) throws Exception {  
  78.         try {  
  79.             testService.dao(id);  
  80.         } catch(Exception be) {  
  81.             throw new BusinessException("{errorCode: 10001, errorMessage: \"错误信息\"}");  
  82.         }  
  83.     }  
  84.     ……  
  85. }  


若是ajax可使用一些代码处理
Java代码   收藏代码
  1. import java.io.IOException;  
  2.   
  3. import javax.servlet.http.HttpServletResponse;  
  4.   
  5. import net.sf.json.JSONObject;  
  6.   
  7. import com.kedacom.common.Message;  
  8.   
  9. public class AjaxUtils {  
  10.     public static void rendText(HttpServletResponse response, String content)  
  11.         throws IOException {  
  12.         response.setCharacterEncoding("UTF-8");  
  13.         response.getWriter().write(content);  
  14.     }    
  15.       
  16.     public static void rendJson(HttpServletResponse response, boolean success, String message) throws IOException{  
  17.         JSONObject json = new JSONObject();  
  18.         json.put("isSuccess", success());  
  19.         json.put("message", message);  
  20.         rendText(response, json.toString());  
  21.     }  
  22. }  
  23.   
  24. @Controller  
  25. public class TestController {  
  26.     @Resource  
  27.     private TestService testService;  
  28.       
  29.     @RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)  
  30.     public void controllerAjax(HttpServletResponse response, Integer id) throws Exception {  
  31.         try {  
  32.             testService.dao(id);  
  33.             AjaxUtils.rendJson(response, true"操作成功");  
  34.         } catch(Exception be) {  
  35.             AjaxUtils.rendJson(response, false"操作");  
  36.         }  
  37.     }  
  38.     ……  
  39. }  
10 楼  snailxr 2013-07-31    引用
楼主,controller里里面有的方法是返回到页面,但是有的方法如果存在异常的话需要通过json返回异信息,这个有木有好的解决方案
9 楼  cgs1999 2013-04-22    引用
zf95834073 写道
非常感谢,问题已经圆满解决了,并且迁入到了框架里,领导也夸我啦,哈哈哈哈~~~~~


呵呵呵~~,替你高兴,解决了就好:D
8 楼  zf95834073 2013-04-22    引用
非常感谢,问题已经圆满解决了,并且迁入到了框架里,领导也夸我啦,哈哈哈哈~~~~~
7 楼  cgs1999 2013-04-18    引用
sunwang810812 写道
佩服楼主,估计永远也达不到楼主的水平了,受益匪浅!!!!!感谢中


我相信努力你也可以做到,甚至比我好~~。

其实本文也是参考了很多前辈的文章,在此感谢。
6 楼  cgs1999 2013-04-18    引用
zf95834073 写道
麻烦再问一下,我使用的是SimpleMappingExceptionResolver这个方式,我理解的是,统一异常处理,是不是dao层抛出异常到service,service再抛出到controller,最终统一处理呢,如果在controller统一处理,那为什么dao,service还要用try catch呢,那样岂不是每个方法都要有try catch了吗,我之前以为如果统一异常处理,代码中就不需要try catch了,我的理解是不是根本就是错误的呢,谢谢


1、你的理解是对的。
   异常处理是一层一层往上抛,最终通过指定的异常处理方式统一处理。

2、为什么dao、service和controller还要用try...catch?
   其实可以不用try...catch
   使用try...catch,主要是统一规范捕获的异常处理,对异常可以捕获后不往上抛,或转换捕获到的异常为较明确的异常继续往上抛出
   举个例子NullPointerException,若不做处理,用户在界面上会直接看到Exception信息,但作为终端用户,他是不清楚到底是怎么回事。但如果在controller、service、dao等转换成“用户不存在或已被删除”、“会议已被取消”等这样的信息是不是更好更清楚呢?
5 楼  sunwang810812 2013-04-16    引用
佩服楼主,估计永远也达不到楼主的水平了,受益匪浅!!!!!感谢中
4 楼  zf95834073 2013-04-16    引用
麻烦再问一下,我使用的是SimpleMappingExceptionResolver这个方式,我理解的是,统一异常处理,是不是dao层抛出异常到service,service再抛出到controller,最终统一处理呢,如果在controller统一处理,那为什么dao,service还要用try catch呢,那样岂不是每个方法都要有try catch了吗,我之前以为如果统一异常处理,代码中就不需要try catch了,我的理解是不是根本就是错误的呢,谢谢
3 楼  zf95834073 2013-04-16    引用
谢谢了,非常非常感谢~~~
2 楼  cgs1999 2013-04-15    引用
zf95834073 写道
您好,我按着您的例子,已经配置到我的项目里了,但是我实际运用的时候,怎么用呢,能贴几个实际使用controller,serveice,dao的方法带捕获异常的方法吗,谢谢~~~


实际应用中,“3.3 集成异常处理 ”部分,只需要根据实际处理需要,选择集成一种方式即可。另,结合“3.4 未捕获异常的处理”部分,处理404和500的错误。

若仅需提示异常信息,推荐使用“3.3.1 使用SimpleMappingExceptionResolver实现异常处理”,该方式简单、扩展方便、松耦合。

实际使用的方法,实际上在范例代码中已给出。Spring MVC异常处理都是对controller层抛出的异常进行处理的,所以对于dao、service的异常只需要一层一层的往上抛到controller层,然后在Controller层抛出该异常即可。

特别注意
(1)可在dao、service和controller层try...catch底层抛上来的异常,然后根据需要转化为其它的异常继续往上抛;
(2)不要在dao、service和controller层把异常给try...catch后而不往上抛异常,这样Spring MVC框架是处理不到异常的。

鉴于范例代码测试成分比较大,可能不是很明了,现修改一下代码:
Java代码   收藏代码
  1. @Repository("userDao")  
  2. public class UserDao {  
  3.     public void getById(Integer id) throws Exception {  
  4.         try {  
  5.             ...  
  6.         } catch(Exception e) {  
  7.             throw new BusinessException("用户不存在");  
  8.         }  
  9.     }  
  10.     public void create(User user) throws Exception {  
  11.         try {  
  12.             ...  
  13.         } catch(Exception e) {  
  14.             throw new BusinessException("保存失败");  
  15.         }  
  16.     }  
  17.     public void update(User user) throws Exception {  
  18.         try {  
  19.             ...  
  20.         } catch(Exception e) {  
  21.             throw new BusinessException("修改失败");  
  22.         }  
  23.     }  
  24.     public void delete(Integer id) throws Exception {  
  25.         try {  
  26.             ...  
  27.         } catch(Exception e) {  
  28.             throw new BusinessException("删除失败");  
  29.         }  
  30.     }  
  31. }  
  32.   
  33.   
  34.   
  35.   
  36.   
  37. public interface UserService {  
  38.     public void getById(Integer id) throws Exception;  
  39.     public void create(User user) throws Exception;  
  40.     public void update(User user) throws Exception;  
  41.     public void delete(Integer id) throws Exception;  
  42. }  
  43.   
  44. @Service("userService")  
  45. public class UserServiceImpl implements UserService {  
  46.     @Resource  
  47.     private UserDao userDao;  
  48.   
  49.     @Override  
  50.     public void getById(Integer id) throws Exception {  
  51.         ...  
  52.         userDao.getById(id);  
  53.     }  
  54.   
  55.     @Override  
  56.     public void create(User user) throws Exception {  
  57.         try{  
  58.             ...  
  59.             userDao.create(user);  
  60.         } catch(Exception e) {  
  61.             throw new BusinessException("创建用户失败,原因...");  
  62.         }  
  63.     }  
  64.   
  65.     @Override  
  66.     public void update(User user) throws Exception {  
  67.         try{  
  68.             ...  
  69.             userDao.update(user);  
  70.         } catch(Exception e) {  
  71.             throw new BusinessException("修改用户失败,原因...");  
  72.         }  
  73.     }  
  74.   
  75.     @Override  
  76.     public void delete(Integer id) throws Exception {  
  77.         try{  
  78.             ...  
  79.             userDao.delete(id);  
  80.         } catch(Exception e) {  
  81.             throw new BusinessException("删除用户失败,原因...");  
  82.         }  
  83.     }  
  84. }  
  85.   
  86.   
  87.   
  88.   
  89.   
  90. @Controller  
  91. public class UserController {  
  92.     @Resource  
  93.     private UserService userService;  
  94.       
  95.     @RequestMapping(value = "/getById.do", method = RequestMethod.GET)  
  96.     public void getById(HttpServletResponse response, Integer id) throws Exception {  
  97.         try{  
  98.             ...  
  99.             userService.getById(id);  
  100.         } catch(Exception e) {  
  101.             throw new ParameterException("参数不正确");  
  102.         }  
  103.     }  
  104.       
  105.     @RequestMapping(value = "/create.do", method = RequestMethod.POST)  
  106.     public void create(HttpServletResponse response, User user) throws Exception {  
  107.         ...  
  108.         userService.create(user);  
  109.     }  
  110.       
  111.     @RequestMapping(value = "/update.do", method = RequestMethod.POST)  
  112.     public void update(HttpServletResponse response, User user) throws Exception {  
  113.         ...  
  114.         userService.update(user);  
  115.     }  
  116.       
  117.     @RequestMapping(value = "/delete.do", method = RequestMethod.POST)  
  118.     public void delete(HttpServletResponse response, Integer id) throws Exception {  
  119.         ...  
  120.         userService.delete(id);  
  121.     }  
  122. }  
1 楼  zf95834073 2013-04-12    引用
您好,我按着您的例子,已经配置到我的项目里了,但是我实际运用的时候,怎么用呢,能贴几个实际使用controller,serveice,dao的方法带捕获异常的方法吗,谢谢~~~
相关文章
|
1月前
|
XML Java 数据库连接
spring boot 参数的过滤注解与实战
在Spring Boot应用中,对于入参的过滤,通常会涉及到对Web层的数据验证和处理。Spring Boot借助Spring框架提供了强大的验证框架支持,主要基于JSR-303/JSR-380(Bean Validation API)规范,以及Spring自身的@Valid或@Validated注解来实现请求参数的验证。以下是一些常见的使用案例来展示如何对参数进行过滤和验证。
29 1
|
26天前
|
安全 Java 数据安全/隐私保护
【深入浅出Spring原理及实战】「EL表达式开发系列」深入解析SpringEL表达式理论详解与实际应用
【深入浅出Spring原理及实战】「EL表达式开发系列」深入解析SpringEL表达式理论详解与实际应用
59 1
|
26天前
|
存储 XML 缓存
【深入浅出Spring原理及实战】「缓存Cache开发系列」带你深入分析Spring所提供的缓存Cache功能的开发实战指南(一)
【深入浅出Spring原理及实战】「缓存Cache开发系列」带你深入分析Spring所提供的缓存Cache功能的开发实战指南
60 0
|
12天前
|
数据采集 前端开发 Java
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
数据塑造:Spring MVC中@ModelAttribute的高级数据预处理技巧
23 3
|
12天前
|
存储 前端开发 Java
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
会话锦囊:揭示Spring MVC如何巧妙使用@SessionAttributes
14 1
|
12天前
|
前端开发 Java Spring
数据之桥:深入Spring MVC中传递数据给视图的实用指南
数据之桥:深入Spring MVC中传递数据给视图的实用指南
29 3
|
12天前
|
Java 数据库 Spring
切面编程的艺术:Spring动态代理解析与实战
切面编程的艺术:Spring动态代理解析与实战
26 0
切面编程的艺术:Spring动态代理解析与实战
|
22天前
|
前端开发 安全 Java
使用Java Web框架:Spring MVC的全面指南
【4月更文挑战第3天】Spring MVC是Spring框架的一部分,用于构建高效、模块化的Web应用。它基于MVC模式,支持多种视图技术。核心概念包括DispatcherServlet(前端控制器)、HandlerMapping(请求映射)、Controller(处理请求)、ViewResolver(视图解析)和ModelAndView(模型和视图容器)。开发流程涉及配置DispatcherServlet、定义Controller、创建View、处理数据、绑定模型和异常处理。
使用Java Web框架:Spring MVC的全面指南
|
28天前
|
敏捷开发 监控 前端开发
Spring+SpringMVC+Mybatis的分布式敏捷开发系统架构
Spring+SpringMVC+Mybatis的分布式敏捷开发系统架构
65 0
|
28天前
|
Java 编译器 API
Spring Boot 异常处理
Java异常分为 Throwable 类的两个子类:Error 和 Exception。Error 是不可捕获的,由JVM处理并可能导致程序终止,如 OutOfMemoryError。Exception 是可捕获的,包括运行时异常如 ArrayIndexOutOfBoundsException 和编译时异常如 IOException。
13 1