使用自定义注解和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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值