JsonResult类的代码
/**
* 通用JsonResult
*/
@Data
public class JsonResult<T> {
private static final long serialVersionUID =-123847128341023033L;
@JSONField
private boolean success = true;
@JSONField
private String message = null;
@JSONField
private String errorCode = "0";
@JSONField
private String errorMsg = null;
@JSONField
private Integer total = 0;
@JSONField
private List<T> data = new ArrayList();
public JsonResult() {
}
/**
* 当有异常时,直接throw一个实现ErrorCode的异常类
* 通过global异常处理器,就可以把jsonResult封装起来,这样代码简洁优美
*/
public JsonResult(BaseException exception) {
if (exception != null) {
success = false;
errorCode = exception.getErrorCode();
errorMsg = exception.getErrorMsg();
}
}
/**
* 虽然很多人都写为isSuccess(),但强烈不建议,因为相当于getSuccess()
* 可以用idea的自动生成下,如果有isSuccess(),就不会生成getSuccess()
*/
public boolean successFlag() {
return success;
}
public JsonResult(List<T> data) {
if (data != null && data.size() > 0) {
this.data = data;
}
}
public JsonResult(T data) {
if (data != null) {
this.data.add(data);
}
}
}
成功的情况下如何封装
用如下封装方式:
List<String> list =new ArrayList<>();
JsonResult<String> jsonResult = new JsonResult<>(list); //直接把data放到里面了
jsonResult.setTotal(list.size());
失败的情况下的封装(手动封装)
失败情况下一般设置3个字段即可(data是不需要的):
success: false
code: -1 或对应的错误码
message: 错误提示
JsonResult<String> jsonResult = new JsonResult<>();
//异常时 success字段,code字段一定要记得重置。 因为success默认是true,code默认为0
jsonResult.setSuccess(false);
jsonResult.setErrorCode("-1");
jsonResult.setErrorMsg("系统异常"); // 这个字段一般也需要
//异常情况下data和total一般不需要
失败情况下抛异常让全局异常处理器处理
思路:
1、代码错误时抛出一个包含code和message的exception类。
2、全局拦截器拦截异常并封装返回jsonResult。
BaseException 大体如下:
@Data
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 6599301895983119239L;
String errorCode;
String errorMsg;
public BaseException(String errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
代码中这么写:
Object object=null;
if(object==null){
throw new BaseException("-1","系统异常");
}
异常拦截器获取到异常放到jsonResult中返回,代码如下:
BaseException baseException=new BaseException("-1","系统异常"); // 这个模拟拦截器捕获到的异常
JsonResult jsonResult = new JsonResult(baseException); // 直接放到json里面即可,(构造的时候会设置success,code,message)
return jsonResult;
这其实也能解决很多人反映的service里面写很多if,return的问题。