背景
相信大部分后端開發(fā)人員在日常開發(fā)中都需要和前端對接,當(dāng)然前后端都是你自己一個人搞的話可以想怎么玩就怎么玩,但是我們還是要做到一定的規(guī)范性。在前后端分離的項(xiàng)目中后端返回的格式一定要友好,并且固定,不能經(jīng)常變來變?nèi)?,不然會對前端的開發(fā)人員帶來很多的工作量。
SpringBoot Controller 常見的返回格式
String
@PostMapping("/test")
public String test(){
return "Hello World";
}
復(fù)制代碼
postman調(diào)用結(jié)果:
自定義對象
正常返回
@PostMapping("/getUser")
public ActionResult getUser(){
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setName("MrDong");
user.setAge(20);
return ActionResult.defaultOk(user);
}
復(fù)制代碼
postman調(diào)用結(jié)果:
錯誤返回
@PostMapping("/error")
public ActionResult error(){
return ActionResult.defaultFail(1000,"服務(wù)器異常,請聯(lián)系管理員");
}
復(fù)制代碼
postman調(diào)用結(jié)果:
定義返回對象
我定義兩個ActionResult這個對象來對返回值進(jìn)行封裝,可以根據(jù)自己公司實(shí)際情況修改:
package com.wxd.entity;
import com.wxd.enums.ResultCodeEnum;
import lombok.Data;
/**
* @ClassName ActionResult
* @Description 統(tǒng)一返回值封裝
* @Author Mr Dong
* @Date 2022/7/26 14:51
*/
@Data
public class ActionResult {
private Integer code;
private String msg;
private Integer count;
private Object data;
public static ActionResult defaultOk(Integer code, String msg, Integer count, Object data) {
return new ActionResult(code, msg, count, data);
}
public static ActionResult defaultOk(Integer count, Object data) {
return new ActionResult(ResultCodeEnum.RC200, count, data);
}
public static ActionResult defaultOk(Object data) {
return new ActionResult(ResultCodeEnum.RC200, null, data);
}
public static ActionResult defaultOk() {
return new ActionResult(ResultCodeEnum.RC200);
}
public static ActionResult defaultFail() {
return new ActionResult(ResultCodeEnum.RC999);
}
public static ActionResult defaultFail(Integer code, String msg) {
return new ActionResult(code, msg);
}
public static ActionResult defaultFail(ResultCodeEnum resultCodeEnum) {
return new ActionResult(resultCodeEnum);
}
public ActionResult(Integer code, String msg, Integer count, Object data) {
this.code = code;
this.msg = msg;
this.count = count;
this.data = data;
}
public ActionResult(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public ActionResult(ResultCodeEnum resultCodeEnum) {
this.code = resultCodeEnum.getCode();
this.msg = resultCodeEnum.getMessage();
}
public ActionResult(ResultCodeEnum resultCodeEnum, Integer count, Object data) {
this.code = resultCodeEnum.getCode();
this.msg = resultCodeEnum.getMessage();
this.count = count;
this.data = data;
}
}
復(fù)制代碼
定義狀態(tài)枚舉
package com.wxd.enums;
/**
* @author wxd
* @version V1.0
* @description ResultCodeEnum
* @date 2022/8/10 13:35
**/
public enum ResultCodeEnum {
/**
* 操作成功
*/
RC200(200, "操作成功"),
/**
* 未授權(quán)
*/
RC401(401, "用戶未授權(quán)"),
/**
* 請求被禁止
*/
RC403(403, "請求被禁止"),
/**
* 服務(wù)異常
*/
RC500(500, "服務(wù)器異常,請聯(lián)系管理員"),
/**
* 操作失敗
*/
RC999(999, "操作失敗"),
RC1001(1001, "用戶名密碼錯誤"),
RC1002(1002, "未授權(quán)的資源"),
RC1003(1003, "未授權(quán)的資源"),
RC1004(1004, "缺少請求參數(shù)異常"),
RC1005(1005, "缺少請求體參數(shù)異常"),
RC1006(1006, "參數(shù)綁定異常"),
RC1007(1007, "方法參數(shù)無效異常");
private Integer code;
private String message;
ResultCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
復(fù)制代碼
統(tǒng)一處理返回值及異常
實(shí)現(xiàn)原理:需要實(shí)現(xiàn)SpringBoot提供的ResponseBodyAdvice這個接口,完成統(tǒng)一返回值的封裝及異常的處理。實(shí)現(xiàn)了這個接口之后,在Controller返回的時候只需要將對象直接返回,有些不需要返回值的可以直接返回void。
package com.wxd.advice;
import com.wxd.entity.ActionResult;
import com.wxd.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* @version: V1.0
* @author: wxd
* @description: 全局異常處理以及返回值的統(tǒng)一封裝
* @Date 2022/7/26 16:24
*/
@RestControllerAdvice(value = "com.wxd.controller")
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
return true;
}
/**
* 統(tǒng)一包裝
*
* @param o
* @param methodParameter
* @param mediaType
* @param aClass
* @param serverHttpRequest
* @param serverHttpResponse
* @return
*/
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
/**
* String、ActionResult不需要再包一層(不想包一層ActionResult對象的可以在這里把這個對象過濾掉)
*/
if (o instanceof String || o instanceof ActionResult) {
return o;
}
return ActionResult.defaultOk(o);
}
/**
* 系統(tǒng)內(nèi)部異常捕獲
*
* @param e
* @return
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = Exception.class)
public Object exceptionHandler(Exception e) {
log.error("系統(tǒng)內(nèi)部異常,異常信息", e);
return ActionResult.defaultFail(ResultCodeEnum.RC500);
}
/**
* 忽略參數(shù)異常處理器;觸發(fā)例子:帶有@RequestParam注解的參數(shù)未給參數(shù)
*
* @param e 忽略參數(shù)異常
* @return ResponseResult
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public Object parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
log.error("缺少Servlet請求參數(shù)異常", e);
return ActionResult.defaultFail(ResultCodeEnum.RC1004);
}
/**
* 缺少請求體異常處理器;觸發(fā)例子:不給請求體參數(shù)
*
* @param e 缺少請求體異常
* @return ResponseResult
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public Object parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
log.error("參數(shù)請求體異常", e);
return ActionResult.defaultFail(ResultCodeEnum.RC1005);
}
/**
* 統(tǒng)一處理請求參數(shù)綁定錯誤(實(shí)體對象傳參);
*
* @param e BindException
* @return ResponseResult
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public Object validExceptionHandler(BindException e) {
log.error("方法參數(shù)綁定錯誤(實(shí)體對象傳參)", e);
return ActionResult.defaultFail(ResultCodeEnum.RC1006);
}
/**
* 統(tǒng)一處理請求參數(shù)綁定錯誤(實(shí)體對象請求體傳參);
*
* @param e 參數(shù)驗(yàn)證異常
* @return ResponseResult
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({MethodArgumentNotValidException.class})
public Object parameterExceptionHandler(MethodArgumentNotValidException e) {
log.error("方法參數(shù)無效異常(實(shí)體對象請求體傳參)", e);
return ActionResult.defaultFail(ResultCodeEnum.RC1007);
}
}
復(fù)制代碼
void 無返回值
有返回值
文章來源:http://www.zghlxwxcb.cn/news/detail-506151.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-506151.html
到了這里,關(guān)于一文教你處理SpringBoot統(tǒng)一返回格式的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!