Skip to content

Commit 6ed36f4

Browse files
committed
feat: 添加接口返回 null 时的返回格式处理,抛出异常
1 parent 6c33dde commit 6ed36f4

1 file changed

Lines changed: 9 additions & 3 deletions

File tree

src/main/java/top/cadecode/simple/common/response/SimpleResAdvice.java

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import org.springframework.http.server.ServerHttpResponse;
77
import org.springframework.web.bind.annotation.ControllerAdvice;
88
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
9+
import top.cadecode.simple.common.exception.SimpleException;
10+
import top.cadecode.simple.constant.ErrorEnum;
911
import top.cadecode.simple.util.JsonUtil;
1012

1113
/**
@@ -23,17 +25,21 @@ public boolean supports(MethodParameter returnType, Class converterType) {
2325
@Override
2426
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
2527
Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
26-
2728
// 获取请求路径
2829
String path = request.getURI().getPath();
29-
// 根据 body 类型分别处理
30+
// 判断 body 是否是 null
31+
if (body == null) {
32+
throw new SimpleException(ErrorEnum.RES_BODY_INVALID, "接口返回结果为空,path 为 " + path);
33+
}
34+
// 判断 body 是否是包装好的 SimpleRes
3035
if (body instanceof SimpleRes) {
3136
return ((SimpleRes) body).path(path);
3237
}
33-
// String 类型的 Body 需要返回 String 类型,否则报转换错误
38+
// 判断 body 是否是包装好的字符串
3439
if (body instanceof String) {
3540
// 设置统一的 Content-Type
3641
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
42+
// String 类型的 Body 需要返回 String 类型,否则报转换错误
3743
return JsonUtil.objToStr(SimpleRes.ok(body).path(path));
3844
}
3945
return SimpleRes.ok(body).path(path);

0 commit comments

Comments
 (0)