@ControllerAdvice 配合 @ExceptionHandler 实现全局异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 *  * 全局异常处理
 * 对RestController和Controller注解的类进行异常捕获 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
 
    /**
     * 异常处理方法
     * 对SQLIntegrityConstraintViolationException这个类型的异常进行拦截
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
 
        /*
        对错误信息进行筛选,确保是重复昵称导致的sql错误
        错误信息格式为 Duplicate entry 'xxx' for key 'xxxxxx'
         */
        if(ex.getMessage().contains("Duplicate entry")){
            //获取重复昵称
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
 
}

  

posted @   小超和你  阅读(102)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
点击右上角即可分享
微信分享提示