Unified exception handling in projects

Table of contents

1: exception handling

1.1: Abnormal problem analysis

1.2: Unified exception handling implementation

1.2.1: Global exception handler

1.2.2: Custom exception class

1.2.3: Unified response front-end exception information encapsulation class

1.2.4: General exception information enumeration class

1.2.5: Testing 


1: exception handling

1.1: Abnormal problem analysis

In the service method, there are many parameter validity checks. When the parameters are illegal, an exception will be thrown. Next, we will test the exception handling.

Request to create course basic information, the required fields are intentionally left blank.

The test found that a 500 exception was reported, as follows:

 It is obviously not acceptable to display such an error message on the client side.

Problem: The exception information specified when we throw the exception is not output.

Therefore, now our requirement is to return data according to the interface requirements during normal operation, and to obtain abnormal information for recording and prompt to the user when the process is abnormal.

In addition to outputting in the log, the exception handling also needs to be prompted to the user. The front end and the back end need to make some agreements:

1. The error message is uniformly returned to the front end in json format.

2. Use the HTTP status code to determine whether there is an error at the moment, and if it is not 200, it means the operation is abnormal.

How to standardize exception information?

The custom exception types of the project are uniformly thrown in the code, so that this type or several types of exceptions can be captured uniformly.

After standardizing the exception type, you can get the exception information.

If a non-project-defined exception type is caught, the user will be prompted with the error message "The execution process is abnormal, please try again".

How to catch the exception?

The code is uniformly captured by try/catch. The code is relatively bloated. You can use the controller enhancement class provided by SpringMVC to uniformly capture exceptions by one class.

As shown below:

1.2: Unified exception handling implementation

According to the solution analyzed above, unified exception handling is realized in the base infrastructure project, and all modules can be used depending on the base infrastructure project.

First add the dependent packages in the base project:

Java
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

1.2.1: Global exception handler

 From Spring 3.0 to Spring 3.2, the exception capture of the Spring architecture and SpringMVC Controller provides corresponding exception handling.

  • @ExceptionHandler
  • The annotation provided by Spring 3.0 on the method or class is used to indicate the exception type of the method.
  • @ControllerAdvice
  • The new annotations provided by Spring 3.2, as can be seen from the name, generally mean controller enhancement, which is used to enhance the Controller in SpringMVC in the project. Usually used in conjunction with @ExceptionHandler  to handle SpringMVC exception information.
  • @ResponseStatus
  • The annotation provided by Spring 3.0 identifies the method or class, and marks the method or exception class with the status code and the reason that should be returned.
    The status code will be applied to the HTTP response when the handler method is called.
/**
 * @author 爱吃豆的土豆
 * @version 1.0
 * @description TODO
 * @date 2023/2/12 17:01
 */
@Slf4j
@ControllerAdvice
//@RestControllerAdvice
public class GlobalExceptionHandler {

 //对项目的自定义异常类型进行处理
   @ResponseBody
   @ExceptionHandler(XueChengPlusException.class)
   @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
 public RestErrorResponse customException(XueChengPlusException e){

    //记录异常
    log.error("系统异常{}",e.getErrMessage(),e);
    //..

    //解析出异常信息
    String errMessage = e.getErrMessage();
    RestErrorResponse restErrorResponse = new RestErrorResponse(errMessage);
    return restErrorResponse;
   }


   @ResponseBody
   @ExceptionHandler(Exception.class)
   @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
 public RestErrorResponse exception(Exception e){

    //记录异常
    log.error("系统异常{}",e.getMessage(),e);

    //解析出异常信息
    RestErrorResponse restErrorResponse = new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrorMessage());

    return restErrorResponse;
   }
}

1.2.2: Custom exception class


/**
 * @author 爱吃豆的土豆
 * @description 本项目自定义异常类型
 */
public class XueChengPlusException extends RuntimeException {

    private String errMessage;

    public XueChengPlusException() {
    }

    public XueChengPlusException(String message) {
        super(message);
        this.errMessage = message;

    }

    public String getErrMessage() {
        return errMessage;
    }

    public void setErrMessage(String errMessage) {
        this.errMessage = errMessage;
    }

    /**
     * 传入自定义异常信息
     * @param message
     */
    public static void cast(String message){
        throw new XueChengPlusException(message);
    }
    /**
     * 重载了一下方法,调用规定好的枚举异常类中的信息
     * @param error
     */
    public static void cast(CommonError error){
        throw new XueChengPlusException(error.getErrorMessage());
    }
}

1.2.3: Unified response front-end exception information encapsulation class

/**
 * @author 爱吃豆的土豆
 * @version 1.0
 * @description 和前端约定返回的异常信息模型
 * @date 2023/2/12 16:55
 */
public class RestErrorResponse implements Serializable {

 private String errMessage;

 public RestErrorResponse(String errMessage){
  this.errMessage= errMessage;
 }

 public String getErrMessage() {
  return errMessage;
 }

 public void setErrMessage(String errMessage) {
  this.errMessage = errMessage;
 }
}

1.2.4: General exception information enumeration class

/**
 * @Author 爱吃豆的土豆、
 * @Date 2023/4/22 15:44
 * @desc 系统执行过程中出现的异常信息
 */
public enum CommonError {
    UNKOWN_ERROR("执行过程异常,请重试。"),
    PARAMS_ERROR("非法参数"),
    OBJECT_NULL("对象为空"),
    QUERY_NULL("查询结果为空"),
    REQUEST_NULL("请求参数为空");

    private String errorMessage;

     CommonError(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}

1.2.5: Testing 

Guess you like

Origin blog.csdn.net/m0_64550837/article/details/130306414