首页 > 其他分享 >统一返回格式

统一返回格式

时间:2023-02-17 16:02:02浏览次数:27  
标签:返回 ResponseDTO return Object pageInfoDTO 格式 data public 统一

统一返回格式

打屁股

MyResponseAdvice

@RestControllerAdvice("com.xhlin.controller")
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 返回true 才允许执行beforeBodyWrite()方法
        return true;
    }

    /**
     * 处理异常
     * @PARAM E
     * @RETURN
     */
    @ExceptionHandler
    public Object processException(Exception e){// 判断异常
        if (e instanceof BizException){
            return   ResponseDTO.fail(((BizException)e).getCode(),e.getMessage());
        }
        // 其他异常
        return ResponseDTO.fail(1,e.getMessage());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Object data = null;
        //从ThreadLocal获取数据
        PageInfoDTO pageInfoDTO = PageInfoLocal.get();
        if (pageInfoDTO != null){
            long total = pageInfoDTO.getTotal();
            Dict dict = Dict.create()
                    .set("total",total)
                    .set("data",body);
            data = ResponseDTO.succeed(dict);
            //清除数据
            PageInfoLocal.clean();
        }else {

           data = ResponseDTO.succeed(body);
        }


        //针对返回类型是String的接口,我们做了特殊的处理
        if (selectedConverterType == StringHttpMessageConverter.class){
            return JSONUtil.toJsonStr(data);
        }

        return data;
    }


}

标签:返回,ResponseDTO,return,Object,pageInfoDTO,格式,data,public,统一
From: https://www.cnblogs.com/xhlin/p/17130458.html

相关文章