1.接口返回值枚举定义
public enum RestCodeEnum {
SUCCESS("200", "处理成功"),
ERROR("500", "系统异常");
private String code;
private String msg;
RestCodeEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
2.异常信息抛出返回值定义
public class RestException extends RuntimeException {
private static final long serialVersionUID = -649224303322031383L;
private RestCodeEnum retCode;
public RestException() {
super();
}
public RestException(RestCodeEnum retCode) {
super(retCode.getMsg());
this.retCode = retCode;
}
public RestException(RestCodeEnum retCode, String msg) {
super(msg);
this.retCode = retCode;
}
public RestCodeEnum getRetCode() {
return this.retCode;
}
public void setRetCode(RestCodeEnum retCode) {
this.retCode = retCode;
}
}
3.接口统一返回参数定义
@Slf4j
public abstract class BaseController {
public static final String CODE = "code";
public static final String MSG = "msg";
public static final String DATA = "data";
protected static String success() {
final Map<String, Object> result = Maps.newHashMap();
result.put(CODE, RestCodeEnum.SUCCESS.getCode());
result.put(MSG, RestCodeEnum.SUCCESS.getMsg());
return JSON.toJSONString(result);
}
protected static String success(Object data) {
final Map<String, Object> result = Maps.newHashMap();
result.put(CODE, RestCodeEnum.SUCCESS.getCode());
result.put(MSG, RestCodeEnum.SUCCESS.getMsg());
result.put(DATA, data);
return JSON.toJSONString(result);
}
protected static String error(RestCodeEnum code) {
final Map<String, Object> result = Maps.newHashMap();
result.put(CODE, code.getCode());
result.put(MSG, code.getMsg());
return JSON.toJSONString(result);
}
protected static String error(RestCodeEnum code, String msg) {
final Map<String, Object> result = Maps.newHashMap();
result.put(CODE, code.getCode());
result.put(MSG, msg);
return JSON.toJSONString(result);
}
}
4.增加全局异常
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends BaseController {
@ExceptionHandler(RestException.class)
public String baseException(RestException e) {
return error(e.getRetCode(), e.getMessage());
}
}
5.实例
@RestController
@RequestMapping("/dataProcessing")
public class DataProcessingController extends BaseController {
@Resource
private JdbcTemplate jdbcTemplate;
@PostMapping("/deleteSource")
public String deleteSource(@RequestBody JSONObject body) {
String sqlCode = body.getString("sqlCode");
if (StringUtils.isBlank(sqlCode)) {
throw new RestException(RestCodeEnum.ERROR);
}
if (jdbcTemplate.update("UPDATE `data_sql` SET `status` = '0' where `sql_code` = '" + sqlCode + "';") > 0) {
return success();
}
return error(RestCodeEnum.ERROR);
}
}