springboot 返回json_SpringBoot统一异常处理返回JSON

代码结构:

a600f586cae4ed8a30ff2e68aa7e05a1.png

统一返回类:

public class DefaultResult implements Serializable {    private static final long serialVersionUID = -8166394979459023084L;    public static final int CODE_SUCCESS = 0;    public static final int CODE_ERROR = 1;    public static final String STR_SUCCESS = "SUCCESS";    public static final String STR_ERROR = "ERROR";    private int code = DefaultResult.CODE_SUCCESS;    private String msg = DefaultResult.STR_SUCCESS;    private T Data;//省略构造函数、get/set、toString}

全局Exception:

public class GlobalException extends Exception {    private static final long serialVersionUID = 6208687918940925747L;    private int errorCode;    private String errorStr;//省略构造函数、get/set、toString}

全局异常处理类:

@ControllerAdvicepublic class GlobalExceptionHandler {    @ExceptionHandler(value = GlobalException.class)    @ResponseBody    public DefaultResult errorJson(GlobalException e) {        DefaultResult result = new DefaultResult<>();        result.setCode(e.getErrorCode());        result.setMsg(e.getErrorStr());        result.setData("");        return result;    }}

测试用结果类:

public class UserResult implements Serializable {    private static final long serialVersionUID = 984326944850108129L;    private long id;    private String userName;/省略构造函数、get/set、toString}

Controller:

@RestControllerpublic class HelloController {    @RequestMapping("/hello")    public DefaultResult hello(            @RequestParam(value = "type", required = false) String type) throws GlobalException {        if (Objects.nonNull(type) && type.equals("error")) {            throw new GlobalException(666, "人为错误");        } else {            UserResult ur = new UserResult();            ur.setId(111);            ur.setUserName("测试");            DefaultResult result = new DefaultResult();            result.setData(ur);            return result;        }    }}

结果:

68902435047390d56dd3b96e2fd00f0c.png
f4fe89f27894c8d61813ad9d1aee0de1.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值