自定义注解和springAOP捕获Service层异常,并处理自定义异常操作

网友投稿 711 2023-01-13

自定义注解和springAOP捕获Service层异常,并处理自定义异常操作

自定义注解和springAOP捕获Service层异常,并处理自定义异常操作

一 自定义异常

/**

* 自定义参数为null异常

*/

public class NoParamsException extends Exception {

//用详细信息指定一个异常

public NoParamsException(String message){

super(message);

}

//用指定的详细信息和原因构造一个新的异常

public NoParamsExcephttp://tion(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;

}

}

即可捕获改异常,并自定义处理逻辑!

捕获SexerPGrvice层异常,统一处理

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

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:浅谈抛出异常和捕获异常的一些区别
下一篇:小程序生态及前景(微信小程序开发前景)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~