import com.alibaba.fastjson.JSONObject;
import com.slst.common.constant.ResponseConstant;
import com.slst.common.exception.BusinessException;
/**
* 结果JSON对象
*
*/
public class ResultJSONObject {
public static JSONObject success() {
JSONObject resultJSONObject = new JSONObject();
resultJSONObject.put(ResponseConstant.key.code,ResponseConstant.code.success);
resultJSONObject.put(ResponseConstant.key.message, ResponseConstant.message.success);
return resultJSONObject;
}
public static JSONObject success(String message) {
JSONObject resultJSONObject = new JSONObject();
resultJSONObject.put(ResponseConstant.key.code,ResponseConstant.code.success);
resultJSONObject.put(ResponseConstant.key.message, message);
return resultJSONObject;
}
public static JSONObject success(String message, Object data) {
JSONObject resultJSONObject = new JSONObject();
resultJSONObject.put(ResponseConstant.key.code, ResponseConstant.code.success);
resultJSONObject.put(ResponseConstant.key.message, message);
resultJSONObject.put(ResponseConstant.key.data, data);
return resultJSONObject;
}
public static JSONObject failed(String message) {
JSONObject resultJSONObject = new JSONObject();
resultJSONObject.put(ResponseConstant.key.code,ResponseConstant.code.failure);
resultJSONObject.put(ResponseConstant.key.message, message);
return resultJSONObject;
}
public static JSONObject failed(String message, Object data) {
JSONObject resultJSONObject = new JSONObject();
resultJSONObject.put(ResponseConstant.key.code, ResponseConstant.code.failure);
resultJSONObject.put(ResponseConstant.key.message, message);
resultJSONObject.put(ResponseConstant.key.data, data);
return resultJSONObject;
}
public static JSONObject failed(Exception e) {
JSONObject resultJSONObject = new JSONObject();
resultJSONObject.put(ResponseConstant.key.code, e instanceof BusinessException ?((BusinessException)e).getCode():ResponseConstant.code.error);
resultJSONObject.put(ResponseConstant.key.message, e.getMessage());
return resultJSONObject;
}
}
响应常量,供参考
/**
* 响应常量
*/
public interface ResponseConstant {
interface key {
String code="code";
String message="message";
String data="data";
}
/**
* 响应码
*/
interface code {
//成功
Integer success = 200;
//失败
int failure = 400;
//错误
int error = 500;
//登录状态异常
int loginStatusError = 999;
}
业务异常处理类: BusinessException
应用场景
@RequestMapping("/test")
public JSONObject test(HttpServletRequest request) {
logger.info(request.getRequestURI());
JSONObject json=null;
try {
//业务逻辑
json = ResultJSONObject.success(ResponseConstant.message.success,data);
} catch (Exception e) {
e.printStackTrace();
json = ResultJSONObject.failed(e);
}
return json;
}