Project unified exception handling

Background exception handling

In the development process, it is inevitable to deal with various exceptions. Exception handling methods can be seen everywhere, so a large number of try {...} catch {...} finally {...}code blocks will appear in the code, which will not only cause a lot of redundant code, but also affect the readability of the code. Therefore, unified handling of exceptions is very necessary. To this end, we have defined a unified exception class YamiShopBindExceptionand exception management class DefaultExceptionHandlerConfig.

Let's look at the YamiShopBindExceptioncode

public class YamiShopBindException extends RuntimeException {
    
    

    private static final long serialVersionUID = -4137688758944857209L;

    /**
     * http状态码
     */
    private Integer httpStatusCode;

    /**
     * @param httpStatus http状态码
     */
    public YamiShopBindException(YamiHttpStatus httpStatus) {
    
    
        super(httpStatus.getMsg());
        this.httpStatusCode = httpStatus.value();
    }

    /**
     * @param httpStatus http状态码
     */
    public YamiShopBindException(YamiHttpStatus httpStatus, String msg) {
    
    
        super(msg);
        this.httpStatusCode = httpStatus.value();
    }

    public YamiShopBindException(String msg) {
    
    
        super(msg);
        this.httpStatusCode = HttpStatus.BAD_REQUEST.value();
    }

    public Integer getHttpStatusCode() {
    
    
        return httpStatusCode;
    }

}

YamiHttpStatusFor our custom enumeration class that returns status codes, it is defined as an enumeration class, which can handle the status code and abnormal content returned by exceptions more intuitively. Every time an exception is added in the future, only one enumeration instance needs to be added. It is not necessary to define an exception class for every exception.

public enum YamiHttpStatus {
    
    
    /**
     * 客户端看到401状态码时,应该重新登陆
     */
    UNAUTHORIZED(401, "未授权"),

    COUPONCANNOTUSETOGETHER(601, "优惠券不能共用"),
    ;

    private final int value;

    private final String msg;

    YamiHttpStatus(int value, String msg) {
    
    
        this.value = value;
        this.msg = msg; 
    }

    public int value() {
    
    
        return this.value;
    }

    public String getMsg() {
    
    
        return msg;
    }
    
    public static YamiHttpStatus resolve(int statusCode) {
    
    
        for (YamiHttpStatus status : values()) {
    
    
            if (status.value == statusCode) {
    
    
                return status;
            }
        }
        return null;
    }
}

Let's look at DefaultExceptionHandlerConfigclass

@Controller
@RestControllerAdvice
public class DefaultExceptionHandlerConfig {
    
    
    

    @ExceptionHandler(YamiShopBindException.class)
    public ResponseEntity<String> unauthorizedExceptionHandler(YamiShopBindException e){
    
    
        e.printStackTrace();
        return ResponseEntity.status(e.getHttpStatusCode()).body(e.getMessage());
    }
}

Foreground exception handling

The front-end request is encapsulated with the corresponding response, and the content of the request response will be intercepted by the interceptor. When the backend returns a specific status code to the frontend, the frontend will display different error messages. Request response is very common, we look at src\utils\httpRequest.jsone of the codes in it

http.interceptors.response.use(response => {
    
    
  return response
}, error => {
    
    
  switch (error.response.status) {
    
    
    case 400:
      Message.error(error.response.data)
      break
    case 401:
      clearLoginInfo()
      router.push({
    
     name: 'login' })
      break
    case 405:
      Message.error('http请求方式有误')
      break
    case 500:
      Message.error('服务器出了点小差,请稍后再试')
      break
    case 501:
      Message.error('服务器不支持当前请求所需要的某个功能')
      break
  }
  return Promise.reject(error)
})

Here, the returned status codes will be intercepted uniformly 400, such as error prompts.

RESTful style

Our above code uses http status codes to uniformly respond to requests, the largest of which

RESTful architecture is currently the most popular Internet software architecture. It has a clear structure, conforms to standards, is easy to understand, and is easy to expand, so it is being adopted by more and more websites.

RESTful overview

Guess you like

Origin blog.csdn.net/lmsfv/article/details/106068560