这篇文章主要为大家展示了“自定义注解和springAOP捕获Service层异常并处理自定义异常的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“自定义注解和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;
}
}
即可捕获改异常,并自定义处理逻辑!
新增注解,实现类和方法层级的异常捕获
package com.ahdruid.aop.annotation;
import java.lang.annotation.*;
/**
* 服务异常捕获,如捕获Service向外抛出的异常
* <p>
* 添加在类上、方法上
*
*/
@Documented
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceExcepCatch {
}
package com.ahdruid.aop;
import com.ahdruid.ReturnMsg;
import com.ahdruid.errorenums.BaseErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* 服务异常捕获处理器
* <p>
* 如捕获Service向外抛出的异常
*
*/
@Component
@Aspect
@Slf4j
public class ServiceExcepHandler {
@Around("@annotation(com.ahdruid.aop.annotation.ServiceExcepCatch) || @within(com.ahdruid.aop.annotation.ServiceExcepCatch)")
public ReturnMsg serviceExcepHandler(ProceedingJoinPoint proceedingJoinPoint) {
ReturnMsg returnMsg = new ReturnMsg();
try {
returnMsg = (ReturnMsg) proceedingJoinPoint.proceed();
} catch (Throwable throwable) {
log.error("ServiceExcepHandler serviceExcepHandler failed", throwable);
returnMsg.setError(BaseErrorEnum.SYS_ERROR_UNKNOW);
}
return returnMsg;
}
}
使用时,在类或者方法上加上注解@ServiceExcepCatch
以上是“自定义注解和springAOP捕获Service层异常并处理自定义异常的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。