文章目录
- 一、背景
- 二、解决方案
一、背景
今天使用postman在做接口测试的时候发现了一个有趣的问题:响应体的status和http的status一样,出于好奇对该现象进行了总结。
二、解决方案
通过拦截器ResponseBodyAdvice,做到统一拦截
@ControllerAdvice(basePackages = "*.*.*")
@RestControllerAdvice(basePackages = "*.*.*")
public class GlobalBizResponseBodyAdvice implements ResponseBodyAdvice {@Overridepublic boolean supports(MethodParameter methodParameter, Class aClass) {return true;}@Overridepublic Object beforeBodyWrite(Object obj, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {if (obj instanceof BizResponse) {int code = (int) ((BizResponse) body).getCode();response.setStatusCode(HttpStatus.valueOf(code));return obj;}response.setStatusCode(HttpStatus.valueOf(200));return BizResponse.success(obj);}