springboot項目controller統(tǒng)一返回對象格式以及全局自定義異常方式
一、需求背景
1.在web接口開發(fā)時,每個模塊接口返回數(shù)據(jù)格式需做封裝,如果每個模塊的返回格式不同,前端需要最不同數(shù)據(jù)格式的適配,使得整個項目很雜亂。如果對接口的返回數(shù)據(jù)做統(tǒng)一封裝就解決此類問題。
2.項目的運(yùn)行時異常,例如用戶名錯誤此類的提示性異常,需要對此類異常做統(tǒng)一性封裝。
二、方法
解決方法
問題一:使用@ControllerAdvice注解,以及實(shí)現(xiàn)ResponseBodyAdvice接口,從而實(shí)現(xiàn)攔截后再封裝邏輯
問題二:使用@ControllerAdvice和@ExceptionHandler注解配合使用,從而捕獲自定義異常類,實(shí)現(xiàn)邏輯的再處理。
三、具體實(shí)現(xiàn)
/**
*封裝的接口統(tǒng)一返回對象
*/
@Data
public class ResultPo<T> {
private int code;
private String msg;
private T data;
public static<T> ResultPo<T> success(T t){
ResultPo<T> resultPo = new ResultPo<>();
resultPo.setCode(ResponseCodeEnum.SUCCESS.getCode());
resultPo.setMsg(ResponseCodeEnum.SUCCESS.getMessage());
resultPo.setData(t);
return resultPo;
}
public static ResultPo error(int code,String msg){
ResultPo resultPo = new ResultPo();
resultPo.setCode(code);
resultPo.setMsg(msg);
return resultPo;
}
}
// 自定義異常類
@Getter
public class BusinessException extends RuntimeException{
private String msg;
private int code;
public BusinessException(String msg){
super(msg);
this.msg =msg;
this.code = ResponseCodeEnum.FAIL.getCode();
}
public BusinessException(String msg,int code){
super(msg);
this.msg =msg;
this.code = code;
}
}
@ResponseBody
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
Logger log = LoggerFactory.getLogger(ResponseAdvice.class);
// 自定義異常捕獲
@ExceptionHandler(BusinessException.class)
public ResultPo customException(BusinessException bs){
ResultPo resultPo = new ResultPo();
resultPo.setCode(bs.getCode());
resultPo.setMsg(bs.getMsg());
resultPo.setData(null);
return resultPo;
}
/**
*return turn 代表此接口會進(jìn)入beforeBodyWrite方法,進(jìn)行邏輯處理
*/
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return !returnType.getDeclaringClass().getName().contains("springfox");
// return true;
}
@Nullable
@Override
public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
// 如果接口返回為string類型,則需要單獨(dú)處理
if(returnType.getGenericParameterType().equals(String.class)){
ObjectMapper objectMapper = new ObjectMapper();
try {
HttpHeaders headers = response.getHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return objectMapper.writeValueAsString(ResultPo.success(body));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
// 接口出現(xiàn)自定義異常,已被customException方法捕獲,則無需再次封裝
if(returnType.getGenericParameterType().equals(ResultPo.class)){
return body;
}
return ResultPo.success(body);
}
}
四、遇到的問題
當(dāng)項目中使用swagger時,會攔截swagger的相關(guān)請求
出現(xiàn)的原因:@ControllerAdvice注解會攔截@Controller以及@RestController標(biāo)記的接口,而swagger的接口是web接口,也是帶有@RestController相關(guān)接口
解決方法:
1.對swagger進(jìn)行放行,就是上面代碼中那樣,放行帶有springfox字樣的接口
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return !returnType.getDeclaringClass().getName().contains("springfox");
// return true;
}
2.自定義一個注解,在需要統(tǒng)一返回值的接口上添加上自定義注解,然后@ControllerAdvice根據(jù)自定義注解進(jìn)行攔截
// ResponseResult為自定義注解 @ControllerAdvice(annotations = ResponseResult.class)
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- SpringBoot @RestController注解用法及說明
- SpringBoot controller接收txt文本文件實(shí)現(xiàn)方式
- SpringBoot攔截器執(zhí)行后,Controller層不執(zhí)行的問題及解決
- SpringBoot中@RestControllerAdvice 全局異常處理的實(shí)現(xiàn)
- Springboot Controller接口默認(rèn)自動填充業(yè)務(wù)實(shí)體參數(shù)值詳解
- SpringBoot之@Controller和@RequestMapping的實(shí)現(xiàn)原理解讀
- SpringBoot和MybatisPlus實(shí)現(xiàn)通用Controller示例
相關(guān)文章
Springboot中com.mysql.cj.jdbc.Driver在yml文件中爆紅的原因解讀
這篇文章主要介紹了Springboot中com.mysql.cj.jdbc.Driver在yml文件中爆紅的原因解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
SpringBoot項目使用Liquibase數(shù)據(jù)庫版本管理方式
Liquibase是開源數(shù)據(jù)庫版本管理工具,支持多數(shù)據(jù)庫及多格式變更日志,實(shí)現(xiàn)變更追蹤、上下文執(zhí)行、文檔生成等功能,需配置目錄結(jié)構(gòu)及master.xml文件,注意@PostConstruct初始化順序問題,建議用CommandLineRunner替代2025-09-09
Java實(shí)現(xiàn)讀取html文本內(nèi)容并按照格式導(dǎo)出到excel中
這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)讀取html文本提取相應(yīng)內(nèi)容按照格式導(dǎo)出到excel中,文中的示例代碼講解詳細(xì),需要的可以參考下2024-02-02

