自定义全局异常
/**
* 全局异常处理
*/
@Data
public class BizException extends RuntimeException {
private Integer code;
private String msg;
public BizException(Integer code, String message) {
super(message);
this.code = code;
this.msg = message;
}
public BizException(BizCodeEnum bizCodeEnum) {
super(bizCodeEnum.getMessage());
this.code = bizCodeEnum.getCode();
this.msg = bizCodeEnum.getMessage();
}
}
自定义异常处理器
@ControllerAdvice
@Slf4j
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public JsonData Handle(Exception e) {
if (e instanceof BizException) {
BizException bizException = (BizException) e;
log.info("[业务异常]{}", e);
return JsonData.buildCodeAndMsg(bizException.getCode(), bizException.getMsg());
} else {
log.info("[非业务异常]{}", e);
return JsonData.buildError("全局异常,未知错误");
}
}
}
使用
模拟异常(改造Controller层)
@GetMapping("/find/{address_id}")
public JsonData detail(@PathVariable("address_id")Long addressId){
int i = 1 / 0;
AddressDO addressDO = addressService.detail(addressId);
return JsonData.buildSuccess(addressDO);
}
@GetMapping("/find/{address_id}")
public JsonData detail(@PathVariable("address_id")Long addressId){
//int i = 1 / 0;
if(addressId == 1) {
throw new BizException(-1,"测试自定义异常");
}
AddressDO addressDO = addressService.detail(addressId);
return JsonData.buildSuccess(addressDO);
}
标签:code,自定义,JsonData,handler,处理器,异常,public,BizException
From: https://www.cnblogs.com/xiaoyangabc/p/17039850.html