網(wǎng)站版本功能列表seo免費(fèi)資源大全
背景
前后端分離情況下,后端接口通常只需要返回JSON數(shù)據(jù)。
但有時(shí)候因?yàn)?strong>某些原因可能會(huì)導(dǎo)致得不到正確的結(jié)果。
比如
因?yàn)榈卿浢艽a錯(cuò)誤,你不能直接返回錯(cuò)誤信息和null,這樣前端很難處理。
又比如
因?yàn)楹蠖私涌诒隽水惓?#xff0c;也不能直接把異常信息返回給前端。
我們需要給返回結(jié)果包上一層:
{ code: 0, message = "信息", data = 返回結(jié)果}
- code :用于判斷響應(yīng)類型。
- message :用于顯示錯(cuò)誤信息。
- data : 返回響應(yīng)結(jié)果
SpringBoot配置
1、定義通用的響應(yīng)體 - MyResponse
public record MyResponse<T>(int code,String message,T data) {}
2、定義響應(yīng)處理器 - MyResponseHandler
將返回結(jié)果封裝到MyResponse實(shí)例。
@RestControllerAdvice
public class MyResponseHandler implements ResponseBodyAdvice<Object> {@Overridepublic boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {//如果返回true,就可以不對(duì)這個(gè)returnType進(jìn)行增強(qiáng)return false;}@Overridepublic Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {// 如果是MyResponse直接返回if (body instanceof MyResponse) {return body;}if (body instanceof String) {return body;}return new MyResponse(0,null,body);}
}
3、定義異常響應(yīng)處理器 - MyResponseHandler
@ExceptionHandler :攔截某個(gè)異常,對(duì)該異常進(jìn)行處理,返回處理后的信息
@RestControllerAdvice
public class MyExceptionHandler {@ExceptionHandler(IOException.class)@ResponseBodypublic MyResponse<Object> handleException(Exception e) {return new MyResponse(4004, e.getMessage(), null);}
}
這樣簡(jiǎn)單的響應(yīng)配置就做好,在實(shí)際項(xiàng)目還需要根據(jù)自己需求進(jìn)行處理。