Springmvc exception handling

Keywords: Spring JSP xml Maven

1 Description
In the development of J2EE project, it is inevitable to encounter all kinds of predictable and unpredictable exceptions that need to be handled, whether it is the database operation process at the bottom, the business process or the control process. Exceptions are handled separately in each process. The code coupling of the system is high, the workload is large and not uniform, and the workload of maintenance is also large.  
Then, can all types of exception handling be decoupled from each processing process, which not only ensures that the functions of the relevant processing process are relatively single, but also achieves the unified processing and maintenance of exception information? The answer is yes. The following section describes the solution and implementation of using Spring MVC to unify exception handling.  

2 Analysis
Spring MVC handles exceptions in three ways:
(1) SimpleMapping Exception Resolver, a simple exception handler provided by Spring MVC;
(2) Implementing Spring exception handling interface Handler Exception Resolver to customize its own exception handler;
(3) Using @ExceptionHandler annotation to implement exception handling;

3 actual combat
3.1 introduction
In order to verify the actual effect of the three exception handling methods of Spring MVC, we need to develop a test project, which throws different exceptions from Dao layer, Service layer and Controller layer respectively, and then integrates the three methods separately to deal with exceptions, so as to compare the advantages and disadvantages of the three methods.  

3.2 Practical Projects
3.2.1 Project Structure
 

3.2.2 Dao Layer Code
  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 Layer Code
  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 Layer Code
  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 page code
  1. <%@ page contentType="text/html; charset=UTF-8"%>  
  2. <html>  
  3. <head>  
  4. <title>Maven Demo</title>  
  5. </head>  
  6. <body>  
  7. <h1>All demonstration examples</h1>  
  8. <h3>[url=./dao.do?id=1]Dao Normal error[/url]</h3>  
  9. <h3>[url=./dao.do?id=10]Dao Parameter error[/url]</h3>  
  10. <h3>[url=./dao.do?id=]Dao unknown error[/url]</h3>  
  11.   
  12.   
  13. <h3>[url=./service.do?id=1]Service Normal error[/url]</h3>  
  14. <h3>[url=./service.do?id=10]Service Parameter error[/url]</h3>  
  15. <h3>[url=./service.do?id=]Service unknown error[/url]</h3>  
  16.   
  17.   
  18. <h3>[url=./controller.do?id=1]Controller Normal error[/url]</h3>  
  19. <h3>[url=./controller.do?id=10]Controller Parameter error[/url]</h3>  
  20. <h3>[url=./controller.do?id=]Controller unknown error[/url]</h3>  
  21.   
  22.   
  23. <h3>[url=./404.do?id=1]404error[/url]</h3>  
  24. </body>  
  25. </html>  

3.3 Integrated exception handling
3.3.1 Implementing exception handling using SimpleMapping Exception Resolver
1. Add the following to the Spring configuration file applicationContext.xml:
  1. <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  2. Define the defau lt exception handling page and use -> when registering the exception type.
  3.     <property name="defaultErrorView" value="error"></property>  
  4. <! - Defines the variable name used by the exception handling page to get exception information, defau lt name is exception ->.
  5.     <property name="exceptionAttribute" value="ex"></property>  
  6. <! - Defines exceptions that require special handling, using class or full path names as key s and page names as values ->.
  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. <! - Here you can continue to extend the processing of different exception types ->.
  13.         </props>  
  14.     </property>  
  15. </bean>  

2. Start the test project. It is proved that the exception thrown by Dao layer, Service layer and Controller layer (business exception Business Exception, parameter exception Exception and other exception Exception) can accurately display the defined exception handling page, and achieve the goal of unified exception handling.  

3. From the above integration process, it can be seen that using SimpleMapping Exception Resolver for exception handling has the advantages of simple integration, good expansibility and no intrusion to existing code, but this method can only obtain exception information. If there is an exception, it is not suitable for the situation where data other than exception is needed.  

3.3.2 Implementing Handler Exception Resolver Interface Custom Exception Processor
1. Adding the implementation class MyExceptionHandler of Handler ExceptionResolver interface, the code is as follows:
  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.         //Turn to different pages according to different errors  
  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. Add the following to the Spring configuration file applicationContext.xml:
  1. <bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>  

3. Start the test project, and verify that the exception thrown by Dao layer, Service layer and Controller layer (business exception Business Exception, parameter exception Exception and other exception Exception) can accurately display the defined exception handling page, and achieve the goal of unified exception handling.  

4. From the above integration process, it can be seen that using exception processor to implement Handler Exception Resolver interface for exception handling has the advantages of simple integration, good expansibility, no intrusion to existing code and so on. At the same time, when exception handling, it can obtain the object that causes the exception, which is conducive to providing more detailed exception handling information.  

3.3.3 Use @ExceptionHandler annotation to implement exception handling
1. Increase the BaseController class and declare exception handling using the @ExceptionHandler annotation in the class. The code is as follows:
  1. public class BaseController {  
  2.     /** Exception Handler-based exception handling*/  
  3.     @ExceptionHandler  
  4.     public String exp(HttpServletRequest request, Exception ex) {  
  5.           
  6.         request.setAttribute("ex", ex);  
  7.           
  8.         //Turn to different pages according to different errors  
  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. Modify the code so that all Controllers that need exception handling inherit this class. As shown below, the modified TestController class inherits from BaseController:
  1. public class TestController extends BaseController  

3. Start the test project, and verify that the exception thrown by Dao layer, Service layer and Controller layer (business exception Business Exception, parameter exception Exception and other exception Exception) can accurately display the defined exception handling page, and achieve the goal of unified exception handling.  

4. From the above integration process, it can be seen that using @ExceptionHandler annotation to implement exception handling has the advantages of simple integration and good expansibility (only need to inherit the Controller class of exception handling from BaseController) and no need to add Spring configuration. However, this method has intrusiveness to the existing code (need to modify the existing code to make the related classes inherit from BaseController). R) Data other than exceptions cannot be retrieved during exception handling.  

3.4 Processing of uncovered exceptions
For Unchecked Exception, because code is not mandatory capture, it is often ignored. If Unchecked Exception is generated during runtime without corresponding capture and processing in the code, we may have to face embarrassing 404, 500... Wait for the server internal error prompt page.  
We need a comprehensive and effective exception handling mechanism. At present, most servers also support configuring display pages for specific exceptions in Web.xml through <error-page> (Websphere/Weblogic) or <error-code> (Tomcat) nodes. Modify the web.xml file and add the following:
  1. <! - Error Page Definition ->.
  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. <! - Here you can continue to add the processing of server error numbers and corresponding pages to display ->.



4 Solutions

1. Run the home page of the test project as shown in the following figure:





2. Business error display page, as shown in the following figure:





3. Pages with incorrect display of parameters, as shown in the following figure:





4. Unknown error pages, as shown in the following figure:





5. Server internal error page, as shown in the following figure:





5 Summary

In conclusion, Spring MVC integrated exception handling in three ways can achieve the goal of unified exception handling. Comparing the advantages and disadvantages of the three methods, it is recommended to use SimpleMapping Exception Resolver if only simple integration exception handling is needed; if integrated exception handling is needed, it can be more personalized and provide users with more detailed exception information, it is recommended to customize the way to implement Handler Exception Resolver interface; if you do not like Spring configuration file or realize zero configuration, and It is recommended that @ExceptionHandler annotation be used if proper intrusion into the original code is acceptable.  



6 source code

The source code project is shown below. It's a Maven project. If you need to run it, please get the relevant dependency packages by yourself.  

Click here to get the source code 



7 References

[1] Spring MVC unified exception handling method

http://hi.baidu.com/99999999hao/blog/item/25da70174bfbf642f919b8c3.html&nbsp;

[2] Preliminary study on exception handling of Spring MVC

http://exceptioneye.iteye.com/blog/1306150&nbsp;

[3] In-depth study of Spring 3 MVC

http://elf8848.iteye.com/blog/875830&nbsp;

[4] Spring MVC exception handling

http://blog.csdn.net/rj042/article/details/7380442

Posted by Hellbringer2572 on Sun, 07 Apr 2019 10:30:31 -0700