SSM integrated detailed teaching (middle)

insert image description here

3. Exception handler

problem import

Question 1: Exceptions may occur at all levels of the project. At which level is the exception handling code written?

1 Exception introduction

  • Abnormal phenomena will inevitably be encountered in the process of program development, and we cannot allow users to see such page data

image-20210805172011686

  • Common locations and common causes of abnormal phenomena are as follows:
    • Exception thrown inside the framework: caused by non-compliant use
    • Exception thrown by the data layer: caused by external server failure (for example: server access timeout)
    • Exceptions thrown by the business layer: caused by business logic writing errors (for example: traversing business writing operations, resulting in index exceptions, etc.)
    • Exceptions thrown by the presentation layer: caused by rules such as data collection and verification (for example: exceptions caused by mismatched data types)
    • Exception thrown by the tool class: caused by the imprecise writing of the tool class and not being robust enough (for example: the connection that needs to be released has not been released for a long time, etc.)

2 exception handler

2.2.1 Writing exception handlers

@RestControllerAdvice  //用于标识当前类为REST风格对应的异常处理器
public class ProjectExceptionAdvice {
    
    

    //统一处理所有的Exception异常
    @ExceptionHandler(Exception.class)
    public Result doOtherException(Exception ex){
    
    
        return new Result(666,null);
    }
}

Effects of using exception handlers

image-20210805171924452

2.2.2 Introduction to @RestControllerAdvice annotation

  • Name: @RestControllerAdvice

  • type:class annotation

  • Position: Above the controller enhancement class definition for Rest-style development

  • Role: Enhance the controller class developed in Rest style

  • Description: This annotation comes with @ResponseBody annotation and @Component annotation, which have corresponding functions

2.2.3 @ExceptionHandler annotation introduction

  • Name: @ExceptionHandler
  • type:method annotation
  • Location: above the controller method dedicated to exception handling
  • Function: Set the processing plan for the specified exception. The function is equivalent to the controller method. After an exception occurs, the execution of the original controller is terminated and transferred to the current method for execution.
  • Description: This method can make multiple methods to handle the corresponding exceptions according to the exceptions handled

4. Project exception handling plan

problem import

Please tell me the classification of the current exception of the project and how to deal with the corresponding type of exception?

1 Item anomaly classification

  • Business exception (BusinessException)
    • Anomalies generated by normative user behavior
    • Abnormalities caused by irregular user behavior operations
  • System exception (SystemException)
    • Predictable and unavoidable exceptions during project operation
  • Other exceptions (Exception)
    • Exceptions that the programmer did not expect

2 Project exception handling scheme

  • Business exception (BusinessException)
    • Send the corresponding message to the user to remind the standard operation
  • System exception (SystemException)
    • Send a fixed message to the user to appease the user
    • Send specific messages to operation and maintenance personnel to remind maintenance
    • record log
  • Other exceptions (Exception)
    • Send a fixed message to the user to appease the user
    • Send specific messages to programmers to remind maintenance (included in expected range)
    • record log

3 Project exception handling code implementation

3.1 Customize exception classes based on exception classification

3.1.1 Custom project system-level exceptions
//自定义异常处理器,用于封装异常信息,对异常进行分类
public class SystemException extends RuntimeException{
    
    
    private Integer code;

    public Integer getCode() {
    
    
        return code;
    }

    public void setCode(Integer code) {
    
    
        this.code = code;
    }

    public SystemException(Integer code, String message) {
    
    
        super(message);
        this.code = code;
    }

    public SystemException(Integer code, String message, Throwable cause) {
    
    
        super(message, cause);
        this.code = code;
    }
}
3.1.2 Custom project business level exception
//自定义异常处理器,用于封装异常信息,对异常进行分类
public class BusinessException extends RuntimeException{
    
    
    private Integer code;

    public Integer getCode() {
    
    
        return code;
    }

    public void setCode(Integer code) {
    
    
        this.code = code;
    }

    public BusinessException(Integer code, String message) {
    
    
        super(message);
        this.code = code;
    }

    public BusinessException(Integer code,String message,Throwable cause) {
    
    
        super(message, cause);
        this.code = code;
    }
}

3.2 Custom exception coding (continuous supplement)

public class Code {
    
    

	//之前其他状态码省略没写,以下是新补充的状态码,可以根据需要自己补充
    
    public static final Integer SYSTEM_ERR = 50001;
    public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
    public static final Integer SYSTEM_UNKNOW_ERR = 59999;
    public static final Integer BUSINESS_ERR = 60002;
    
}

3.3 Trigger custom exceptions

@Service
public class BookServiceImpl implements BookService {
    
    
    @Autowired
    private BookDao bookDao;

	//在getById演示触发异常,其他方法省略没有写进来
    public Book getById(Integer id) {
    
    
        //模拟业务异常,包装成自定义异常
        if(id <0){
    
    
            throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
        }
    }
}

3.4 Intercept and handle exceptions in the exception notification class

@RestControllerAdvice //用于标识当前类为REST风格对应的异常处理器
public class ProjectExceptionAdvice {
    
    
    //@ExceptionHandler用于设置当前处理器类对应的异常类型
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){
    
    
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(ex.getCode(),null,ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex){
    
    
        return new Result(ex.getCode(),null,ex.getMessage());
    }

    //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
    @ExceptionHandler(Exception.class)
    public Result doOtherException(Exception ex){
    
    
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
    }
}

Test: Send a request to access the getById method in postman, pass the parameter -1, and get the following results:

image-20210805173815730

Guess you like

Origin blog.csdn.net/qq_51808107/article/details/130540953