捕获Service层异常,统一处理

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

package com.ahdruid.aop.annotation;

import java.lang.annotation.*;

/**
 * 服务异常捕获,如捕获Service向外抛出的异常
 * 

* 添加在类上、方法上 * */ @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;

/**
 * 服务异常捕获处理器
 * 

* 如捕获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

你可能感兴趣的:(Java编程)