文章目錄
前言
在 web 開發過程中, 後端要統一返回的數據結構,便於前端處理。例如每個請求,我們都需要知道 :
- code : 服務器返回的狀態碼(主要給程序員看)。例如 : 200 : 請求成功, 500 : 服務器內部錯誤,400 : 未知錯誤
- status : 返回碼 1:成功 10000:系統錯誤 10001:參數錯誤 …
- msg : 服務器的錯誤信息 ,主要返回給用戶看。
- data : 服務器返回的數據。
1、定義通用結構Result.java
package com.ieslab.powergrid.demosvr.entity;
/** <p>Title: PersonService </p>
* <p>Description: 通用Rest請求返回結構 </p>
*
* @author bingge
* @date 2020-2-20 下午7:15:30
* @version V1.0
*/
public class Result {
//服務器返回的狀態碼(主要給程序員看)。例如 : 200 : 請求成功, 500 : 服務器內部錯誤,400 : 未知錯誤
private Integer code;
//返回碼 1:成功 10000:系統錯誤 10001:參數錯誤 ...
private Integer status;
// 服務器的錯誤信息 ,主要返回給用戶看
private String msg;
// 服務器返回的數據
private Object data;
public Result() {
}
//返回操作成功
public static Result ok() {
return ok(null);
}
//返回操作成功
public static Result ok(Object data) {
Result result = new Result();
result.setCode(200);
result.setStatus(1);
result.setMsg("請求成功");
result.setData(data);
return result;
}
//返回操作成功
public static Result error() {
return error("請求失敗");
}
//返回操作成功
public static Result error(Integer code, Integer status, String msg) {
Result result = new Result();
result.setCode(code);
result.setStatus(status);
result.setMsg(msg);
return result;
}
//返回操作成功
public static Result error(String msg) {
return error(500,0, msg);
}
//返回操作成功
public static Result error(ErrorStatus errorStatus) {
return error(500,errorStatus.value(), errorStatus.getMessage());
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
2、通用錯誤碼ErrorStatus.java
package com.ieslab.powergrid.demosvr.entity;
/** <p>Title: PersonService </p>
* <p>Description: 通用Rest請求返回錯誤碼結構 </p>
*
* @author bingge
* @date 2020-2-20 下午7:15:30
* @version V1.0
*/
public enum ErrorStatus {
/**
* 系統內部錯誤
*/
INTERNAL_SERVER_ERROR(10000, "系統錯誤"),
/**
* 參數錯誤
*/
ILLEGAL_ARGUMENT(10001, "參數錯誤"),
/**
* 業務錯誤
*/
SERVICE_EXCEPTION(10002, "業務錯誤"),
/**
* 非法的數據格式,參數沒有經過校驗
*/
ILLEGAL_DATA(10003, "數據錯誤"),
MULTIPART_TOO_LARGE(1004,"文件太大"),
/**
* 非法狀態
*/
ILLEGAL_STATE(10005, "非法狀態"),
/**
* 缺少參數
*/
MISSING_ARGUMENT(10006, "缺少參數"),
/**
* 非法訪問
*/
ILLEGAL_ACCESS(10007, "非法訪問,沒有認證"),
/**
* 權限不足
*/
UNAUTHORIZED(10008, "權限不足"),
/**
* 錯誤的請求
*/
METHOD_NOT_ALLOWED(10009, "不支持的方法"),
/**
* 參數錯誤
*/
ILLEGAL_ARGUMENT_TYPE(10010, "參數類型錯誤");
private final int value;
private final String message;
ErrorStatus(int value, String message) {
this.value = value;
this.message = message;
}
/**
* Return the integer value of this status code.
*/
public int value() {
return this.value;
}
/**
* Return the reason phrase of this status code.
*/
public String getMessage() {
return this.message;
}
}
3、全局異常捕獲GlobleExceptionHandler.java
package com.ieslab.powergrid.demosvr.utils;
import com.ieslab.powergrid.demosvr.entity.MyException;
import com.ieslab.powergrid.demosvr.entity.Result;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/** <p>Title: GlobleExceptionHandler </p>
* <p>Description: 全局異常捕捉處理</p>
*
* @author houpeibin
* @date 2020-2-20 下午7:15:30
* @version V1.0
*/
@ControllerAdvice
public class GlobleExceptionHandler {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Result errorHandler(Exception ex) {
//判斷異常的類型,返回不一樣的返回值
if(ex instanceof MissingServletRequestParameterException){
return Result.error(400, 0, "全局異常捕捉:缺少必需參數:"
+((MissingServletRequestParameterException) ex).getParameterName());
}
else if(ex instanceof MyException){
return Result.error(400, 0, "全局異常捕捉:這是自定義異常");
}
return Result.error(400, 0, "全局異常捕捉:未知異常");
}
}
詳細用法可以參考:Spring Boot2.x:統一異常處理
4、測試RestTestController.java
package com.ieslab.powergrid.demosvr.controller;
import com.ieslab.powergrid.demosvr.entity.ErrorStatus;
import com.ieslab.powergrid.demosvr.entity.Result;
import com.ieslab.powergrid.demosvr.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/rest")
public class RestTestController {
@Autowired
PersonService personService;
@RequestMapping("/index")
public Result getData(String id){
Map map = new HashMap<>();
map.put("id", id);
return Result.ok(personService.getPersons(map));
}
@RequestMapping("/index2")
public Result getData2(){
return Result.error(ErrorStatus.INTERNAL_SERVER_ERROR);
}
@RequestMapping("/index3")
public Result getData3(){
int a = 1/0;
return Result.ok();
}
}
分別訪問:http://localhost:8080/rest/index?id=1
訪問:http://localhost:8080/rest/index2
訪問:http://localhost:8080/rest/index3
5、總結
對於錯誤碼的定義,需要根據業務要求進行詳細定義,這樣,在前後端調試時,可以節省很多的時間,也會避免不必要的扯皮。