一,統(tǒng)一返回數(shù)據(jù)結構
- 定義返回的數(shù)據(jù)結構
package com.futao.springmvcdemo.model.system;
import org.joda.time.DateTime;
import java.sql.Timestamp;
/**
* 統(tǒng)一返回Rest風格的數(shù)據(jù)結構
*
* @author futao
* Created on 2018/9/22-21:47.
*/
public class RestResult {
/**
* 請求是否成功(這個字段不需要,可以不加)
*/
private boolean success;
/**
* 成功或者失敗的code錯誤碼
*/
private String code;
/**
* 成功時返回的數(shù)據(jù),失敗時返回具體的異常信息
*/
private Object data;
/**
* 請求失敗返回的提示信息,給前端進行頁面展示的信息
*/
private Object errorMessage;
/**
* 服務器當前時間(添加該字段的原因是便于查找定位請求時間,因為實際開發(fā)過程中服務器時間可能跟本地時間不一致,加上這個時間戳便于日后定位)
*/
private Timestamp currentTime;
public RestResult() {
}
@Override
public String toString() {
return "RestResult{" +
"success=" + success +
", code='" + code + '\'' +
", data=" + data +
", errorMessage=" + errorMessage +
", currentTime=" + currentTime +
'}';
}
public RestResult(boolean success, String code, Object data, Object errorMessage) {
this.success = success;
this.code = code;
this.data = data;
this.errorMessage = errorMessage;
this.currentTime = new Timestamp(new DateTime().getMillis());
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Object getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(Object errorMessage) {
this.errorMessage = errorMessage;
}
public Timestamp getCurrentTime() {
return currentTime;
}
public void setCurrentTime(Timestamp currentTime) {
this.currentTime = currentTime;
}
}
- 將返回數(shù)據(jù)包裝成Rest風格
實現(xiàn)ResponseBodyAdvice<T>
package com.west.lake.blog.foundation;
import com.lazy.rest.rest.RestResult;
import com.west.lake.blog.annotation.RestSkip;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.swagger.web.ApiResourceController;
import springfox.documentation.swagger2.web.Swagger2Controller;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* 返回Rest風格的數(shù)據(jù)
*
* @author futao
* Created on 2018/9/22-20:24.
*/
@RestControllerAdvice
public class RestResultWrapper implements ResponseBodyAdvice<Object> {
/**
* 不需要攔截的類路徑,這里寫的是Class
* 如果該類所在項目沒有相關的依賴,可以換成String-類的全路徑
*/
private static final List<Class<?>> SKIP_CLASS_LIST = new ArrayList<>(2);
static {
//Swagger
SKIP_CLASS_LIST.add(ApiResourceController.class);
//Swagger
SKIP_CLASS_LIST.add(Swagger2Controller.class);
}
/**
* 可指定針對某些返回值的類型才進行rest風格的封裝
*
* @param returnType 返回值類型
* @param converterType
* @return
*/
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
if (SKIP_CLASS_LIST.contains(returnType.getDeclaringClass())) {
return false;
}
Method returnTypeMethod = returnType.getMethod();
if (returnTypeMethod != null) {
return !returnTypeMethod.isAnnotationPresent(RestSkip.class);
}
return true;
}
/**
* 封裝正常返回的數(shù)據(jù)
*
* @param body
* @param returnType
* @param selectedContentType
* @param selectedConverterType
* @param request
* @param response
* @return
*/
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (MediaType.IMAGE_JPEG.getType().equalsIgnoreCase(selectedContentType.getType())) {
return body;
}
if (body instanceof RestResult) {
return body;
}
return new RestResult(RestResult.SUCCESS_CODE, body, null);
}
}
- 請求測試
@GetMapping("get")
public User get() {
User user = new User();
user.setUsername("NiuBist");
user.setId("123");
user.setAge("18");
user.setEmail("12312@qq.com");
user.setMobile("12312321312");
user.setAddress("浙江省杭州市");
return user;
}
結果:

請求結果
二,統(tǒng)一異常處理,返回統(tǒng)一異常數(shù)據(jù)結構
- 定義一個類來存放所以的異常提示信息,便于管理
package com.futao.springmvcdemo.model.entity.constvar;
/**
* 錯誤提示集合類
* 錯誤碼構成: 01程序員編號
* 001該程序員定義的錯誤碼
* 后面再跟上錯誤信息
*
* @author futao
* Created on 2018/9/21-15:29.
*/
public final class ErrorMessage {
public static final String SYSTEM_EXCEPTION = "系統(tǒng)繁忙,請稍后再試";
public static final String NOT_LOGIN = "01001_您還未登陸或者登陸已超時,請重新登陸";
public static final String MOBILE_ALREADY_REGISTER = "01002_該手機號已經被注冊了";
public static final String LOGIC_EXCEPTION = "01003_對不起,你是真的沒有我?guī)?;
}
- 定義邏輯異常類
package com.futao.springmvcdemo.foundation;
/**
* 業(yè)務邏輯異常類、
*
* @author futao
* Created on 2018/9/20-15:22.
*/
public class LogicException extends RuntimeException {
/**
* 異常信息
*/
private String errorMsg;
/**
* 錯誤碼
*/
private String code;
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private LogicException(String errorMsg) {
super(errorMsg);
this.code = errorMsg.substring(0, 5);
this.errorMsg = errorMsg.substring(6);
}
/**
* 拋出邏輯異常
*
* @param errorMsg
* @return
*/
public static LogicException le(String errorMsg) {
return new LogicException(errorMsg);
}
}
- 對異常(包括系統(tǒng)異常與業(yè)務邏輯異常)進行統(tǒng)一處理
package com.futao.springmvcdemo.foundation;
import com.alibaba.fastjson.JSONObject;
import com.futao.springmvcdemo.model.entity.constvar.ErrorMessage;
import com.futao.springmvcdemo.model.system.RestResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 異常統(tǒng)一處理,
*
* @author futao
* Created on 2018/9/21-15:13.
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Object logicExceptionHandler(HttpServletRequest request, Exception e, HttpServletResponse response) {
//系統(tǒng)級異常,錯誤碼固定為-1,提示語固定為系統(tǒng)繁忙,請稍后再試
RestResult result = new RestResult(false, "-1", e.getMessage(), ErrorMessage.SYSTEM_EXCEPTION);
//如果是業(yè)務邏輯異常,返回具體的錯誤碼與提示信息
if (e instanceof LogicException) {
LogicException logicException = (LogicException) e;
result.setCode(logicException.getCode());
result.setErrorMessage(logicException.getErrorMsg());
} else {
//對系統(tǒng)級異常進行日志記錄
logger.error("系統(tǒng)異常:" + e.getMessage(), e);
}
return JSONObject.toJSON(result);
}
}
- 測試
package com.futao.springmvcdemo.controller;
import com.futao.springmvcdemo.foundation.LogicException;
import com.futao.springmvcdemo.model.entity.constvar.ErrorMessage;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author futao
* Created on 2018/9/23-0:28.
* 統(tǒng)一異常處理測試接口
*/
@RequestMapping(path = "exception", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class ExceptionTestController {
/**
* 業(yè)務邏輯異常
*/
@GetMapping(path = "logicException")
public void logicException() {
throw LogicException.le(ErrorMessage.LOGIC_EXCEPTION);
}
/**
* 系統(tǒng)異常
*/
@GetMapping(path = "systemException")
public void systemException() {
throw new NullPointerException("空指針了,哥門!!!");
}
}

邏輯異常

系統(tǒng)級異常

系統(tǒng)級異常