目录
一、为什么要统一返回?
二、全局异常处理代码
三、统一返回对象代码
四、使用方法
五、结果展示
一、为什么要统一返回?
在Spring Boot应用中,为了保持API接口的响应格式统一,通常会采用全局异常处理和自定义返回对象的方式
二、全局异常处理代码
package com.by.config;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@RestControllerAdvice(basePackages = {"com.by"})
@Slf4j
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
@ExceptionHandler(Exception.class)
public Object processException(Exception ex){
ResponseDTO responseDto = new ResponseDTO();
responseDto.setCode(1);
responseDto.setMsg(ex.getMessage());
return responseDto;
}
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if(body instanceof ResponseDTO){
return body;
}
ResponseDTO responseDto = new ResponseDTO();
responseDto.setCode(0);
responseDto.setMsg("请求成功");
responseDto.setData(body);
if (selectedConverterType == StringHttpMessageConverter.class) {
return JSONUtil.toJsonStr(responseDto);
} else {
return responseDto;
}
}
}
三、统一返回对象代码
默认0代表成功
package com.by.config;
;
public class ResponseDTO {
private int code; // 0,非0 错误码
private String msg; // 如果非0的时候,显示的是错误的信息
private Object data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
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;
}
public static ResponseDTO success(Object data)
{
ResponseDTO responseDTO = new ResponseDTO();
responseDTO.setCode(0);
responseDTO.setData(data);
//返回成功
return responseDTO;
}
public static ResponseDTO error(int code,String msg)
{
ResponseDTO responseDTO = new ResponseDTO();
responseDTO.setCode(code);
responseDTO.setMsg(msg);
return responseDTO;
}
}
四、使用方法
在自己项目中添加如下两个代码即可。
五、结果展示
访问自己的接口时,会统一返回结果