Java returns a unified result set and exception handling

Preface

With the trend of separation of front and back ends, what now needs to be considered is if there is a clear stipulation with the front end, such as: I add a piece of data, the back end is void type when designing, and there is no return value, then how does the front end judge this addition? Was the operation successful? At this time, if there is an agreement, whether it is void or not, we wrap the result in a result set and inform the front-end in the form of code, so that the front-end can judge whether the operation is successful or not?

Example of returning a unified result set

1. First create a Maven project

        <!--   导入spring boot支持  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.6.RELEASE</version>
        </dependency>

2. The class for writing the package result. This class mainly stores a code: used to judge the status of the operation for the front end. message: the result of execution. And data: The data returned to the front end can be an entity class or a string.

Introduce dependencies

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

Create the Result class

package com.zhao.spring.util;

public class Result<T> {
    
    
    /**状态码*/
    private int code;
    /**消息*/
    private String message;
    /**返回的数据*/
    private T data;

    //省略getter和setter

    //省略有参构造方法和无参构造方法

    //省略toString方法
    
    //定义一个枚举
    enum ResultCode{
    
    
        SUCCESS(200,"成功!"),
        BAD(400, "失败!"),
        EMPTY(404,"资源不存在!");

        private int code;
        private String message;

        ResultCode(int code, String message) {
    
    
            this.code = code;
            this.message = message;
        }

        public int getCode() {
    
    
            return code;
        }

        public String getMessage() {
    
    
            return message;
        }
    }
    /**
     * 成功
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(T data){
    
    
        Result<T> result = new Result<>();
        result.code=ResultCode.SUCCESS.getCode();
        result.message=ResultCode.SUCCESS.getMessage();
        result.data=data;
        return result;
    }
}

3. Create a test class

@RestController
public class TestController {
    
    

    @GetMapping("/findAll")
    public Result findAll(@RequestParam("id") Integer id){
    
    
        School school = new School();
        school.setId(id);
        school.setSchoolName("上海理工");
        return Result.success(school);
    }
}

The results of the interview are as follows

Insert picture description here

Exception handling

Exception handling is very important. For example, the parameters passed by the front-end are not received by the back-end. If exception handling is not performed, an error will be reported, so exception handling is required at this time.

1. Create a global exception handling class ErrorCode

public enum ErrorCode {
    
    

    null_id(1051, "nullId", "参数丢失");

    private int status;
    private String code;
    private String reason;

    ErrorCode(int status, String code, String reason) {
    
    
        this.status = status;
        this.code = code;
        this.reason = reason;
    }
   //省略getter和setter方法
}

Add an abnormal return method to the previous result set class Result class

    /**
     * 失败
     * @param <T>
     * @param errorCode
     * @return
     */
    public static <T> Result<T> bad(ErrorCode errorCode){
    
    
        Result<T> result=new Result<>();
        result.code=ResultCode.BAD.getCode();
        result.message=errorCode.getReason();
        result.data=null;
        return result;
    }

3. Then we modify the test method again

@RestController
public class TestController {
    
    

    @GetMapping("/findAll")
    public Result findAll(@RequestParam("id") Integer id,
                          //required = false:允许传递的参数为空
                          @RequestParam(value = "schoolName",required = false) String schoolName){
    
    
        if (schoolName == null){
    
    
            //如果schoolName为null就返回异常:说明参数丢失
            return Result.bad(ErrorCode.null_id);
        }
        School school = new School();
        school.setId(id);
        school.setSchoolName(schoolName);
        return Result.success(school);
    }
}

The returned result is as follows

Insert picture description here

It ends here.

Guess you like

Origin blog.csdn.net/javaasd/article/details/109663331