三个类
import lombok.Data;
import net.xdclass.enums.BizCodeEnum;
import org.apache.ibatis.annotations.Param;
@Data
public class BizException extends RuntimeException {
private int code;
private String msg;
public BizException(int code, String msg){
super(msg);
this.code = code;
this.msg = msg;
}
public BizException(BizCodeEnum bizCodeEnum){
super(bizCodeEnum.getMessage());
this.code = bizCodeEnum.getCode();
this.msg = bizCodeEnum.getMessage();
}
}
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.utils.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
@Slf4j
public class CustomExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public JsonData handle(Exception e){
//是不是自定义异常
if(e instanceof BizException){
BizException bizException = (BizException) e;
log.error("[业务异常 {}]",e);
return JsonData.buildCodeAndMsg(bizException.getCode(),bizException.getMsg());
}else{
log.error("[系统异常 {}]",e);
return JsonData.buildError("全局异常,未知错误");
}
}
}
import lombok.Getter;
/**
* @author DBC
* @date 2022/4/29 9:42
*/
public enum BizCodeEnum {
ORDER_CONFIRM_TOKEN_EQUAL_FAIL(-1,"订单令牌不正确"),
JV_SHUOMING(666666,"举例说明");
@Getter
private String message;
@Getter
private int code;
private BizCodeEnum(int code, String message){
this.code = code;
this.message = message;
}
} 即可看到效果




还可以有这种测试的方法
@ApiOperation("根据ID查找地址详情")
@GetMapping("/find/{address_id}")
public Object detail(
@ApiParam(value = "地址id",required = true)
@PathVariable("address_id") long addressId){
if (addressId==1){
throw new BizException(-1,"测试自定义异常");
}
AddressDO addressDO = addressService.detail(addressId);
return JsonData.buildSuccess(addressDO);
} 



本文作者为DBC,转载请注明。