What are the SpringMVC global exception handling methods?

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-ouppMxKP-1601369928324)(https://imgkr.cn-bj.ufileos.com/50416f44-5b7e-43bb -a0c4-ee71be577c04.jpg)]

In the development of a JavaEE project, whether it is the underlying database operation process, the processing process of the business layer, or the processing process of the control layer, it is inevitable that various predictable and unpredictable exceptions need to be dealt with. Each process handles exceptions separately, the system's code coupling is high, the workload is large and not unified, and the workload of maintenance is also large.

SpringMvc provides support for exception handling. Through the global exception handling mechanism provided by SpringMvc, all types of exception handling can be decoupled from each processing process, which not only ensures the single function of the related processing process, but also realizes exceptions. Unified processing and maintenance of information.

Three ways of SpringMVC global exception handling

  • Use the simple exception handler SimpleMappingExceptionResolver provided by Spring MVC;

  • Implement Spring's exception handling interface HandlerExceptionResolver to customize your own exception handler;

  • Use @ExceptionHandler annotation to achieve exception handling;

Case practice

Global exception handling method one

Configure SimpleMappingExceptionResolver object

<bean class="org.springframework.web.servlet.handler.SimpleMappingException Resolver">
    <property name="defaultErrorView" value="error"></property>
    <property name="exceptionAttribute" value="ex"></property>
    <property name="exceptionMappings">
        <props>
            <prop  key="com.xxx.exception.BusinessException">error1</prop>
            <prop  key="com.xxx.exception.ParamsException">error2</prop>
        </props>
    </property>
</bean>

Using SimpleMappingExceptionResolver for exception handling has the advantages of simple integration, good scalability, and no intrusion to existing code, but this method can only obtain exception information. If an exception occurs, you need to obtain data other than the exception The situation does not apply.

Global exception handling method two

Implement the HandlerExceptionResolver interface

@Component
public class GlobalException implements HandlerExceptionResolver {
    
    
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex) {
    
    
            Map<String,Object> map=new HashMap<String, Object>();
            map.put("ex", ex);
            ModelAndView mv=null;
            if(ex instanceof ParamsException){
    
    
            	return new ModelAndView("error_param", map);
            }
            if(ex instanceof BusinessException){
    
    
            	return new ModelAndView("error_business", map);
            }
        return new ModelAndView("error", map);
    } 
}

Using the exception handler that implements the HandlerExceptionResolver interface for exception handling has the advantages of simple integration, good scalability, and no intrusion to existing code. At the same time, it can obtain the object that caused the exception during exception handling, which is beneficial to provide more Detailed exception handling information.

Global exception handling method three

Page processor inherits BaseController

public class BaseController {
    
    
    @ExceptionHandler
    public String exc(HttpServletRequest request,HttpServletResponse
    response,Exception ex){
    
    
        request.setAttribute("ex", ex);
        if(ex instanceof ParamsException){
    
    
            return "error_param"; 
        }
        if(ex instanceof BusinessException){
    
    
            return "error_business"; 
        }
        return "error";
    } 
}

Using @ExceptionHandler annotation to achieve exception handling has the advantages of simple integration, good scalability (only the Controller class to be exception handling needs to be inherited from BaseController), no additional Spring configuration, etc., but this method is intrusive to existing code (It is necessary to modify the existing code so that the related class inherits from BaseController), and data other than the exception cannot be obtained during exception handling.

Extended ~ uncaught exception handling

For Unchecked Exception, because the code does not force capture, it is often ignored. If the Unchecked Exception is generated during runtime, and the code is not captured and processed accordingly, 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 the configuration of the display page of specific abnormal conditions through the (Websphere/Weblogic) or (Tomcat) node in Web.xml. Modify the web.xml file and add the following content:

<!-- 出错页面定义 -->
<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/500.jsp</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/500.jsp</location>
</error-page>
<error-page>
    <error-code>404</error-code>
    <location>/404.jsp</location>
</error-page>

Guess you like

Origin blog.csdn.net/dirft_lez/article/details/108871761