Back-end development - unified exception handling Spring MVC mechanism

1. Spring MVC’s unified exception handling mechanism

In Spring MVC, there is a unified mechanism for handling exceptions.
The specific performance is as follows: no matter which process of processing the request an exception occurs, each type of exception only needs to write a paragraph Just the code to handle the exception!

The core of unified exception handling is to define methods for handling exceptions:

  • Return value type: Please refer to the method of processing the request
  • Method name: Custom
  • Parameter list: at least includes the exception object being handled. In addition, you can add parameters as needed. When there are multiple parameters, the order of each parameter is not distinguished.
  • Annotation: @ExceptionHandler annotation must be added to indicate that this method is a method for handling exceptions

Createex.handler.GlobalExceptionHandler class under the root package of the project as the "global exception handler" class of the current project.

Add@RestControllerAdvice annotation to the class. The specific methods in this class will be applied to any request processing process in the entire project!
Write the code to handle exceptions uniformly in this class (there is no need to repeat exception handling methods in each controller class):
For example: a>

package com.luoyang.small.ex.handler;

import com.luoyang.small.ex.CustomServiceException;
import com.luoyang.small.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一处理异常
 *
 * @author luoyang
 * @date 2023/12/17
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    

    @ExceptionHandler
    public JsonResult handleServiceException(CustomServiceException e) {
    
    
        log.warn("统一处理CustomServiceException,异常信息:{}", e.getMessage());
        return JsonResult.fail(e);
    }
}

2. Auxiliary code examples

The corresponding CustomServiceException.java

public class CustomServiceException extends RuntimeException {
    
    

    private ServiceCode serviceCode;

    public CustomServiceException(ServiceCode serviceCode, String message) {
    
    
        super(message);
        this.serviceCode = serviceCode;
    }

    public ServiceCode getServiceCode() {
    
    
        return serviceCode;
    }
}

The corresponding ServiceCode.java

public enum ServiceCode {
    
    
    OK(200),
    ERR_NOT_FOUND(404),
    ERR_CONFLICT(409),
    ERR_CUSTOM(1000);

    // 以下属性,表示每个枚举类型的对象都有一个Integer value属性,此属性的值将通过构造方法传入
    private Integer value;
    ServiceCode(Integer value) {
    
    
        this.value = value;
    }

    // 用于通过枚举对象获取Integer value属性的值
    public Integer getValue() {
    
    
        return value;
    }
}

The corresponding JsonResult.java

@Data
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
//@JsonInclude(JsonInclude.Include.NON_NULL) //配置在类上,所以属性为空是都不展示该属性
public class JsonResult implements Serializable {
    
    
    private Integer code;
    private String message;

    public static JsonResult ok() {
    
    
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(ServiceCode.OK.getValue());
        return jsonResult;
    }

    public static JsonResult fail(ServiceCode serviceCode, String message) {
    
    
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(serviceCode.getValue());
        jsonResult.setMessage(message);
        log.error("JsonResult fail  serviceCode {}, message{}", serviceCode, message);
        return jsonResult;
    }

    public static JsonResult fail(CustomServiceException e) {
    
    
        return fail(e.getServiceCode(), e.getMessage());
    }
}

3. Exceptions are thrown everywhere and handled uniformly by one class

CustomServiceException exceptions are thrown everywhere, as follows: GlobalExceptionHandler.handleServiceException is handled uniformly,Insert image description here
When the client submits a request to the server, such as "add photo album", if the server-side controller An exception occurs when calling the Service method in the method that handles the request. However, the method that handles the request does not need to handle this exception, for example:Insert image description here

When the method of processing the request is not usedtry..catch...Catch the exception. If an exception occurs, it is equivalent to the method of processing the request throwing an exception!
Insert image description here

Insert image description here

Note: The key point is to add@RestControllerAdvice annotation to the custom global class (such as GlobalExceptionHandler). Specific methods in this class (such as handleServiceException(CustomServiceException e)) are unified methods for handling exceptions. ) will be applied to any request processing process in the entire project!

Create value and share it happily!
Let’s get started with the backend 204146007

Guess you like

Origin blog.csdn.net/ly_xiamu/article/details/135045823