5.统一返回值类型
程序员文章站
2024-03-14 09:00:28
...
自定义返回类型
package com.gunsmoke.commonUtils;
import lombok.Data;
@Data
public class BaseResult
{
private String code;
private String message;
private boolean status;
private Object data;
private BaseResult() {
}
public static BaseResult success()
{
BaseResult baseResult = new BaseResult();
baseResult.setCode(ResultNum.SUCCESS.getCode());
baseResult.setMessage(ResultNum.SUCCESS.getMessage());
baseResult.setData(null);
return baseResult;
}
public static BaseResult success(Object data)
{
BaseResult baseResult = new BaseResult();
baseResult.setCode(ResultNum.SUCCESS.getCode());
baseResult.setMessage(ResultNum.SUCCESS.getMessage());
baseResult.setData(data);
return baseResult;
}
public static BaseResult error(ResultNum resultNum)
{
BaseResult baseResult = new BaseResult();
baseResult.setCode(resultNum.getCode());
baseResult.setMessage(resultNum.getMessage());
return baseResult;
}
}
枚举类型
/**
* Copyright (c) 2020 ucsmy.com, All rights reserved.
*/
package com.gunsmoke.commonUtils;
public enum ResultNum
{
SUCCESS("200", "成功"),
GLOBAL_ERROR("-1","接口调用错误"),
PARAM_ERROR("201", "参数不合法"),
DATABASE_ERROR("202", "数据库异常");
private String code;
private String message;
ResultNum(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
controller中使用
@Api(description = "讲师管理")
@RestController
@RequestMapping("/eduservice/edu-teacher")
public class EduTeacherController {
@Autowired
private EduTeacherService teacherService;
@ApiOperation(value = "查询所有讲师列表")
@GetMapping("findAll")
public BaseResult findAllTeacher()
{
List<EduTeacher> list = teacherService.list(null);
//return BaseResult.success(list);
return BaseResult.error(ResultNum.GLOBAL_ERROR);
}
}