0
点赞
收藏
分享

微信扫一扫

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


文章目录

  • ​​1. 创建一个枚举、封装异常的错误码等信息​​
  • ​​2. 创建一个自定义异常类继承RuntimeException。​​
  • ​​3. 自定义异常​​
  • ​​4. 抛出异常​​
  • ​​5. 测试​​
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

Springboot全局异常统一处理返回json_抛出异常


举报

相关推荐

0 条评论