使用自定義注解和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;
    }
}

四 使用

 

 即可捕獲改異常,並自定義處理邏輯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM