期望返回的json格式如下

{
  "code": 200,
  "msg": "操作成功",
  "data": "hello jenkins"
}

实现步骤如下

1.自定义状态码枚举类。

@allargsconstructor
@getter
public enum statuscodeenum {
    sc200(200, "操作成功"),
    sc999(999, "操作失败"),
    sc401(401, "匿名用户访问权限资源时的异常"),
    sc403(403, "无访问权限,请联系管理员授予权限"),
    sc404(404, "请求的资源不存在"),
    sc500(500, "系统异常,请稍后重试"),
    // ...略
    private final integer code;
    private final string msg;
}

2.封装返回结果

@data
public class apiresult<t> implements serializable {
    private integer code;
    private string msg;
    private t data;

    public static <t> apiresult<t> success(t data) {
        return apiresult.success(statuscodeenum.sc200.getmsg(), data);
    }

    public static <t> apiresult<t> success(string msg, t data) {
        apiresult<t> apiresult = new apiresult<>();
        apiresult.setcode(statuscodeenum.sc200.getcode());
        apiresult.setmsg(msg);
        apiresult.setdata(data);
        return apiresult;
    }

    public static <t> apiresult<t> fail(integer code, string msg) {
        apiresult<t> apiresult = new apiresult<>();
        apiresult.setcode(code);
        apiresult.setmsg(msg);
        return apiresult;
    }

}

3.全局异常捕获处理,使用@restcontrolleradvice注解。

@slf4j
@restcontrolleradvice
public class globalexceptionhandler {
    /**
     * 捕获其他异常
     */
    @responsestatus(httpstatus.internal_server_error)
    @exceptionhandler(exception.class)
    public apiresult<string> handle(exception e) {
        log.error("全局异常信息:{}", e.getmessage());
        return apiresult.fail(statuscodeenum.sc500.getcode(), statuscodeenum.sc500.getmsg());
    }
}
注解 功能
@restcontrolleradvice restcontroller的增强类,可用于实现全局异常处理器
@exceptionhandler 统一处理某一类异常,从而减少代码重复率和复杂度,比如要获取自定义异常可以@exceptionhandler(businessexception.class)
@responsestatus 指定客户端收到的http状态码

注:请求进来 会按照 filter -> interceptor -> controlleradvice -> aspect -> controller的顺序调用,
404异常(nohandlerfoundexception)是无法通过这种方式捕获的,因为在filter层发生的异常都会到spring默认的异常处理。如果你在配置文件配置了server.error.path的话,就会使用你配置的异常处理地址,如果没有就会使用你配置的error.path路径地址,如果还是没有,默认使用/error来作为发生异常的处理地址。如果想要替换默认的非controller异常处理直接实现spring提供的errorcontroller接口就行了。

4.拦截controller方法的返回值,统一处理返回值/响应体,因为我们后面每写一个接口都需要调用apiresult.success()这行代码对结果进行包装,重复劳动,浪费体力,我们只需要实现springboot提供的responsebodyadvice接口即可。

@restcontrolleradvice
public class apiresultwrapper implements responsebodyadvice<object> {
    /**
     * 是否支持advice功能
     */
    @override
    public boolean supports(methodparameter methodparameter, class<? extends httpmessageconverter<?>> aclass) {
        return true;
    }

    /**
     * 对返回的数据进行处理
     */
    @override
    public object beforebodywrite(object o, methodparameter methodparameter, mediatype mediatype, class<? extends httpmessageconverter<?>> aclass, serverhttprequest serverhttprequest, serverhttpresponse serverhttpresponse) {
        if (o instanceof string) {
            return json.tojsonstring(apiresult.success(o));
        }
        // 这个判断的作用:防止全局异常处理后返回的结果(类型为apiresult)再次被包装
        if (o instanceof apiresult) {
            return o;
        }
        return apiresult.success(o);
    }

}

5.创建controller,定义两个方法,让第二个方法抛异常

@restcontroller
public class testcontroller {
    @getmapping("/test1")
    public string test1() {
        return "当前时间:" + localdatetime.now().format(datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss"));
    }

    @getmapping("/test2")
    public integer test2() {
        system.out.println(1 / 0);
        return integer.max_value;
    }
}

6.分别请求http://localhost:8080/test1、http://localhost:8080/test2,结果如下

在全局异常处理类中写了一行代码

log.error("全局异常信息:{}", e.getmessage());

所以调用test2方法时控制台打印异常信息如下

到此这篇关于springboot返回统一的json标准格式的文章就介绍到这了,更多相关springboot返回json格式内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!