捕获Service层异常,统一处理

新增注解,实现类和方法层级的异常捕获

package com.ahdruid.aop.annotation;

import java.lang.annotation.*;

/**
 * 服务异常捕获,如捕获Service向外抛出的异常
 * <p>
 * 添加在类上、方法上
 *
 */
@Documented
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceExcepCatch {
}

异常处理handler

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值