当前位置: 首页 > news >正文

使用自定义注解和SpringAOP捕获Service层异常,并处理自定义异常

目录

  • 一 自定义异常
  • 二 自定义注解
  • 三 注解切面处理类
  • 四 使用

一 自定义异常

/*** 自定义参数为null异常*/
public class NoParamsException extends Exception {//用详细信息指定一个异常public NoParamsException(String message){super(message);}//用指定的详细信息和原因构造一个新的异常public NoParamsException(String message, Throwable cause){super(message,cause);}//用指定原因构造一个新的异常public NoParamsException(Throwable cause) {super(cause);}
}

二 自定义注解

/*** 统一捕获service异常处理注解*/
@Documented
@Target({ElementType.METHOD, ElementType.TYPE}) //可在类或者方法使用
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceExceptionCatch {
}

三 注解切面处理类

@Component
@Aspect
@Slf4j
public class ServiceExceptionHandler {@Around("@annotation(com.zhuzher.annotations.ServiceExcepCatch)  || @within(com.zhuzher.annotations.ServiceExcepCatch)")public ResponseMessage serviceExceptionHandler(ProceedingJoinPoint proceedingJoinPoint) {ResponseMessage returnMsg;try {returnMsg = (ResponseMessage) proceedingJoinPoint.proceed();} catch (Throwable throwable) {log.error("ServiceExcepHandler serviceExcepHandler failed", throwable);//单独处理缺少参数异常if(throwable instanceof NoParamsException) {returnMsg = ResponseMessage.failture(ErrorCode.ARG_CAN_NOT_BE_EMPTY);}else{//其他正常返回returnMsg=ResponseMessage.newErrorsMessage(throwable.getMessage());}}return returnMsg;}
}

四 使用

在这里插入图片描述
即可捕获该异常,并自定义处理逻辑

原文地址:https://www.cnblogs.com/houzheng/p/11953183.html

http://www.lryc.cn/news/165040.html

相关文章:

  • Kotlin(六) 类
  • 蓝桥杯官网练习题(灌溉)
  • 数据结构:树的概念和结构
  • 【GIS】栅格转面报错:ERROR 000864输入栅格: 输入不在定义的属性域内。 ERROR 000863: 无效的 GP 数据类型
  • 32 WEB漏洞-文件操作之文件下载读取全解
  • Linux之history、tab、alias、命令执行顺序、管道符以及exit
  • vcomp100.dll丢失怎样修复?5个靠谱的修复方法分享
  • Vue3自定义指令(directive)
  • 大数据课程L9——网站流量项目的实时业务处理代码
  • 【2023最新B站评论爬虫】用python爬取上千条哔哩哔哩评论
  • mysql设置max_sp_recursion_depth,sql_mode
  • 论文阅读:SERE: Exploring Feature Self-relation for Self-supervised Transformer
  • 遥感数据与作物模型同化应用:PROSAIL模型、DSSAT模型、参数敏感性分析、数据同化算法、模型耦合、精度验证等主要环节
  • Navicat15工具连接PostgreSQL15失败
  • 开源AI家庭自动化助手-手机控制家庭智能家居服务
  • 解决CSS定位错乱/疑难杂症的终极绝招==》从样式污染开始排查
  • 【笔记】《C++性能优化指南》Ch3 测量性能
  • 2023大数据面试总结
  • udev自动创建设备节点的机制
  • 访问局域网内共享文件时报错0x80070043,找不到网络名
  • Java定时器
  • 科普js加密时出现的错误
  • MYSQL优化——B+树讲解
  • Rokid Jungle--Station pro
  • 如何实现微服务
  • MySQL如何进行增量备份与恢复?
  • 微服务框架
  • (matplotlib)如何让各个子图ax大小(宽度和高度)相等
  • python http 上传文件
  • IPO解读:Instacart曲折上市,业务模式如何持续“绚烂”?