Springboot uniformly handles the return results and exceptions

1. Create the result entity first

  • Example Create interface IErrorCode
public interface IErrorCode {
    /** * returns the status code *@returnReturns the status code */
    Integer getStatus(a);

    /** * Return message *@returnReturn message */
    String getMessage(a);
}
Copy the code
  • Create the enumeration class ResultCode

    public enum ResultCode implements IErrorCode{
        /** * The operation succeeded */
        SUCCESS(200."Operation successful"),
        /** * The operation failed */
        FAILED(500."Operation failed"),
        /** * Failed to check parameters */
        VALIDATE_FAILED(404."Parameter verification failed"),
        UNAUTHORIZED(401."Not logged in or token has expired"),
        FORBIDDEN(403."No relevant authority.");
        private final Integer status;
        private final String message;
    
        private ResultCode(Integer status, String message) {
            this.status = status;
            this.message = message;
        }
    
        @Override
        public Integer getStatus(a) {
            return status;
        }
    
        @Override
        public String getMessage(a) {
            returnmessage; }}Copy the code
  • Create the resulting entity class

    @Data
    @JsonPropertyOrder(value = {"status", "message", "data"})
    public class CommonResult<T> {
    
        /**
         * 请求状态
         */
        private Integer status;
    
        /** * Message */
        private String message;
    
        /** * returns the body type */
        private T data;
    
        public CommonResult(a){}
    
        public CommonResult(String message){
            this.status = 200;
            this.message = message;
        }
    
        public CommonResult(String message, T data) {
            this.status = 200;
            this.message = message;
            this.data = data;
        }
    
        public CommonResult(Integer status, String message, T data){
            this.status = status;
            this.message = message;
            this.data = data;
        }
    
    
        /** * Successfully returns the result **@paramData Obtained data */
        public static <T> CommonResult<T> success(T data) {
            return new CommonResult<T>(ResultCode.SUCCESS.getStatus(), ResultCode.SUCCESS.getMessage(), data);
        }
    
        /** * Successfully returns the result **@paramData Indicates the obtained data *@paramMessage Indicates the prompt message */
        public static <T> CommonResult<T> success(T data, String message) {
            return new CommonResult<T>(ResultCode.SUCCESS.getStatus(), message, data);
        }
    
        /** * Failed to return the result *@paramErrorCode indicates the errorCode */
        public static <T> CommonResult<T> failed(IErrorCode errorCode) {
            return new CommonResult<T>(errorCode.getStatus(), errorCode.getMessage(), null);
        }
    
        /** * Failed to return the result *@paramMessage Indicates the prompt message */
        public static <T> CommonResult<T> failed(String message) {
            return new CommonResult<T>(ResultCode.FAILED.getStatus(), message, null);
        }
    
        /** * Failed to return the result */
        public static <T> CommonResult<T> failed(a) {
            return failed(ResultCode.FAILED);
        }
    
        /** * Parameter verification failure Result */
        public static <T> CommonResult<T> validateFailed(a) {
            return failed(ResultCode.VALIDATE_FAILED);
        }
    
        /** * Parameter verification failed result *@paramMessage Indicates the prompt message */
        public static <T> CommonResult<T> validateFailed(String message) {
            return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getStatus(), message, null);
        }
    
        /** * No login result */
        public static <T> CommonResult<T> unauthorized(T data) {
            return new CommonResult<T>(ResultCode.UNAUTHORIZED.getStatus(), ResultCode.UNAUTHORIZED.getMessage(), data);
        }
    
        /** * Unauthorized return result */
        public static <T> CommonResult<T> forbidden(T data) {
            return newCommonResult<T>(ResultCode.FORBIDDEN.getStatus(), ResultCode.FORBIDDEN.getMessage(), data); }}Copy the code

2. Create custom annotations

@Retention(RUNTIME)
@Target({TYPE, METHOD})
@Documented
public @interface ResponseResult {

}
Copy the code

3. Create class ResponseResultHandler to handle exceptions and return

@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {


    @Override

    public boolean supports(MethodParameter methodParameter, Class
       > converterType) {
        ResponseResult Returns true if there is a comment on the class or method, false if there is not
        returnmethodParameter.getMethodAnnotation(ResponseResult.class) ! =null|| converterType.getAnnotation(ResponseResult.class) ! =null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        /* To annotate a class or method with @responseresult, use the uniform return result entity */
        return CommonResult.success(body);
    }

    /** * Custom unified exception handling */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<Object> methodNotAregumentHandler(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Set<String> errorMessage = new HashSet<>();
        for (FieldError fieldError : fieldErrors){
            errorMessage.add(fieldError.getDefaultMessage());
        }
        return CommonResult.validateFailed(errorMessage.toString());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult<Object> exceptionHandler(Exception e){
        returnCommonResult.failed(ResultCode.FAILED); }}Copy the code