Springboot全局异常统一处理返回json

1. 创建一个枚举、封装异常的错误码等信息
package com.gblfy.distributedlimiter.enums;

public enum ServiceErrCode {

    REQ_PARAM_ERR(10001, "您的手慢了,秒杀完毕!"),
    NOTFOUND_RESULT_ERR(10004, "服务器异常");

    private int code;
    private String msg;

    ServiceErrCode(int code, String msg) {
        this.code = code;
        this.msg = msg;

    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

2. 创建一个自定义异常类继承RuntimeException。
package com.gblfy.distributedlimiter.exception;

import com.gblfy.distributedlimiter.enums.ServiceErrCode;

public class BaseServiceException extends RuntimeException {

    private int code;

    public BaseServiceException(String message, ServiceErrCode serviceErrCode) {//构造器的第二个参数是上面创建的那个枚举,之后把枚举里面定义的code给了这个code
        super(message);
        this.code = serviceErrCode.getCode();
    }

    public int getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return super.getMessage();
    }
}

3. 自定义异常
package com.gblfy.distributedlimiter.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gblfy.distributedlimiter.exception.BaseServiceException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;

/**
 * 标记这是一个异常处理类
 */
@RestControllerAdvice
public class CustomExtHandler {

    @Resource
    private ObjectMapper jsonMapper;

    @ExceptionHandler(BaseServiceException.class)
    public ObjectNode baseServiceException(BaseServiceException e){
        int code = e.getCode();
        String msg = e.getMessage();
        return jsonMapper.createObjectNode().put("code",code).put("msg",msg);
    }
}
4. 抛出异常
package com.gblfy.distributedlimiter.controller;

import com.gblfy.distributedlimiter.enums.ServiceErrCode;
import com.gblfy.distributedlimiter.exception.BaseServiceException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelLimiterController {

    @GetMapping("/excepton")
    public void exceptonHandle() {
        //如果超过流控管理的就抛出异常
        throw new BaseServiceException(ServiceErrCode.REQ_PARAM_ERR.getMsg(), ServiceErrCode.REQ_PARAM_ERR);
    }
}

5. 测试
https://localhost:8080/excepton

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gblfy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值