如何捕获xxxService.java中this.insert()抛出的异常?

来源:10-6 视频授权播放功能开发

慕神4535282

2021-08-06

老师,下午好,请教一个问题?
我用您的框架写一些公司业务时,遇到一些问题,希望可以得到您的指导。

drop table if exists legal_device;
create table legal_device (
  id char(8) not null default '' comment 'id',
  product_name varchar(50) not null comment '产品名称',
  device_id varchar(12) not null comment '设备id',
  primary key (id),
  unique key `device_id_unique` (`device_id`)
) engine=innodb default charset=utf8mb4 comment='合法设备';

有这样一个表,因为

unique key `device_id_unique` (`device_id`)

,当重复插入相同的device_id时,会返回一堆错误,
如图(postman截图):
图片描述
谢谢老师的指导!!!

这是源码的截图:
图片描述

写回答

1回答

甲蛙

2021-08-09

可以在统一异常处理类里ControllerExceptionHandler,对所有的Exception做拦截

/**
 * 校验异常统一处理
 * @param e
 * @return
 */
@ExceptionHandler(value = Exception.class)
@ResponseBody
public CommonResp validExceptionHandler(Exception e) {
    CommonResp commonResp = new CommonResp();
    LOG.error("系统异常:", e);
    commonResp.setSuccess(false);
    commonResp.setMessage("系统出现异常,请联系管理员");
    return commonResp;
}

也可以只拦截这个异常

//img.mukewang.com/szimg/6110fc81098c081f06630137.jpg

0
1
慕神4535282
非常感谢!
2021-08-10
共1条回复

Spring Cloud+ Vue前后端分离开发企业级在线视频系统

全网稀缺课程 市场热门项目+主流框架 一课掌握前后端技术

1743 学习 · 1697 问题

查看课程