Spring MVC ------ exception handling

Keywords: Java Spring Spring MVC mvc

exception handling

Exception handler

Exception classification management

code:

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component//Comment out this sentence, and the exception handler cannot be used
public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler,
                                         Exception ex) {
        System.out.println("my exception is running ...."+ex);
        ModelAndView modelAndView = new ModelAndView();
        if( ex instanceof NullPointerException){
            modelAndView.addObject("msg","Null pointer exception");
        }else if ( ex instanceof  ArithmeticException){
            modelAndView.addObject("msg","Arithmetic operation exception");
        }else{
            modelAndView.addObject("msg","Unknown exception");
        }
        modelAndView.setViewName("error.jsp");
        return modelAndView;
    }
}

Annotation implements exception handling

  • code:

    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Component
    //Developing exception handlers using annotations
    //Declare that this class is a notification class of the Controller. After declaration, this class will be loaded as an exception handler
    @ControllerAdvice//If this sentence is commented out, the exception handler cannot be used
    public class ExceptionAdvice {
    
        //The method defined in the class that carries the @ ExceptionHandler annotation will be treated as an exception handler, followed by the actual exception type
        @ExceptionHandler(NullPointerException.class)//Handle null pointer exception
        @ResponseBody//If you don't write the ResponseBody, it will find the return page. After adding it, it won't be parsed into a page
        public String doNullException(Exception ex){
            return "Null pointer exception";
        }
    
        @ExceptionHandler(ArithmeticException.class)//Handling arithmetic exceptions
        @ResponseBody
        public String doArithmeticException(Exception ex){
            return "ArithmeticException";
        }
    
        @ExceptionHandler(Exception.class)//Handle all exceptions
        @ResponseBody
        public String doException(Exception ex){
            return "all";
        }
    
    }
    

Comparison of two exception handling methods

The annotation processor can intercept the input parameter type conversion exception: in short, the processing time is relatively early, which is loaded before the parameter is converted to the controller

The non annotation processor cannot intercept the input parameter type conversion exception: This is loaded later. The working timing of the two is different. This is relatively late

Project exception handling scheme (understanding)

Anomaly classification

  • Business exception: the user does this

    • Exceptions caused by standardized user behavior: for example, input age, user input - 1
    • Exceptions caused by nonstandard user behavior operations: for example, the user knows the url address of financial approval in the company by accident, directly enters it in the address bar, knocks back, and then approves the money and gets the money
  • System exception:

    • Predictable and unavoidable exceptions during project operation: for example, connection timeout, especially slow network and special card
  • Other exceptions:

    • Unexpected exception of programmers: the code written by programmers is wrong and unpredictable

Exception handling scheme

  • Business exception:

    • Send the corresponding message to the user to remind the standard operation
  • System exception:

    • Send a fixed message to the user to appease the user
    • Send specific messages to the operation and maintenance personnel to remind them of maintenance
    • Log
  • Other exceptions:

    • Send a fixed message to the user to appease the user
    • Send specific messages to programmers to remind maintenance
      • Included in the expected scope
    • Log

Custom exception

  • Test code

    • Custom exception class

      • BusinessException.java

        //The custom exception inherits RuntimeException and overrides all construction methods of the parent class
        public class BusinessException extends RuntimeException {
            public BusinessException() {
            }
        
            public BusinessException(String message) {
                super(message);
            }
        
            public BusinessException(String message, Throwable cause) {
                super(message, cause);
            }
        
            public BusinessException(Throwable cause) {
                super(cause);
            }
        
            public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
                super(message, cause, enableSuppression, writableStackTrace);
            }
        }
        
        
      • SystemException.java system exception

        //The custom exception inherits RuntimeException and overrides all construction methods of the parent class
        public class SystemException extends RuntimeException {
            public SystemException() {
            }
        
            public SystemException(String message) {
                super(message);
            }
        
            public SystemException(String message, Throwable cause) {
                super(message, cause);
            }
        
            public SystemException(Throwable cause) {
                super(cause);
            }
        
            public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
                super(message, cause, enableSuppression, writableStackTrace);
            }
        }
        
    • ajax asynchronous request

      <%@page pageEncoding="UTF-8" language="java" contentType="text/html;UTF-8" %>
      
      <a href="javascript:void(0);" id="testException">visit springmvc backstage controller´╝îtransmit Json format POJO</a><br/>
      
      <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>
      
      <script type="text/javascript">
          $(function () {
              $("#testException").click(function(){
                  $.ajax({
                      contentType:"application/json",
                      type:"POST",
                      url:"save",
                      /*Activate the occurrence of custom exceptions by modifying parameters*/
                      // Business exception occurs when the length of name is less than 8 bits
                      // Business exception when age is less than 0
                      // System exception when age is greater than 100
                      // If the age type cannot be matched, it will be transferred to other category exceptions
                      data:'{"name":"Jock","age":"111"}',
                      dataType:"text",
                      //Callback function
                      success:function(data){
                          alert(data);
                      }
                  });
              });
          });
      </script>
      
    • error.jsp error jump page

      <%--Exception message display page--%>
      <%@page pageEncoding="UTF-8" language="java" contentType="text/html;UTF-8" %>
      ${msg}
      
    • UserController.java

      import com.itheima.domain.User;
      import com.itheima.exception.BusinessException;
      import com.itheima.exception.SystemException;
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestBody;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.ResponseBody;
      
      import java.util.ArrayList;
      import java.util.List;
      
      @Controller
      public class UserController {
          @RequestMapping("/save")
          @ResponseBody
          public List<User> save(@RequestBody User user) {
              System.out.println("user controller save is running ...");
      
              //An exception occurred when the simulated business layer initiated the call
      //        int i = 1/0;
      //        String str = null;
      //        str.length();
      
              //Determine the illegal operation of the user and package it as an abnormal object for processing, which is convenient for unified management
              if(user.getName().trim().length() < 8){
                  throw new BusinessException("Sorry, the user name length does not meet the requirements, please re-enter!");
              }
              if(user.getAge() < 0){
                  throw new BusinessException("Sorry, age must be between 0 and 100!");
              }
              if(user.getAge() > 100){
                  throw  new SystemException("Server connection failed, please check and handle as soon as possible!");
              }
      
      
              User u1 = new User();
              u1.setName("Tom");
              u1.setAge(3);
              User u2 = new User();
              u2.setName("Jerry");
              u2.setAge(5);
              ArrayList<User> al = new ArrayList<User>();
              al.add(u1);
              al.add(u2);
      
              return al;
          }
      }
      
      
    • Exception handler ProjectExceptionAdvice.java

      import org.springframework.stereotype.Component;
      import org.springframework.ui.Model;
      import org.springframework.web.bind.annotation.ControllerAdvice;
      import org.springframework.web.bind.annotation.ExceptionHandler;
      import org.springframework.web.bind.annotation.ResponseBody;
      
      @Component
      @ControllerAdvice
      public class ProjectExceptionAdvice {
      
          @ExceptionHandler(BusinessException.class)
          public String doBusinessException(Exception ex, Model m){
              //Use the parameter Model to transfer the data to be saved to the page. The function is equivalent to ModelAndView
              //Messages with business exceptions should be sent to users for viewing
              m.addAttribute("msg",ex.getMessage());
              return "error.jsp";
          }
      
          @ExceptionHandler(SystemException.class)
          public String doSystemException(Exception ex, Model m){
              //Do not send messages with system exceptions to users for viewing, but send unified information to users for viewing
              m.addAttribute("msg","There is a problem with the server, please contact the administrator!");
              //The actual problem phenomenon should be transmitted to the redis server, and the operation and maintenance personnel can view it through the background system
              //The actual problems should be transmitted to the redis server, and the operation and maintenance personnel can view them through the background system
              return "error.jsp";
          }
      
          @ExceptionHandler(Exception.class)
          public String doException(Exception ex, Model m){
              m.addAttribute("msg",ex.getMessage());
              //Save ex objects
              return "error.jsp";
          }
      
      }
      

Posted by almystersv on Tue, 05 Oct 2021 17:42:20 -0700