67,514
社区成员
发帖
与我相关
我的任务
分享
public class MyException extends Exception
{
static final long serialVersionUID = -7034897190745766939L;
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(Throwable cause) {
super(cause);
}
}
@Aspect
@Component
public class CheckSecurity
{
@Pointcut("execution(* add*(..))")
private void chkAdd() {};
@Before("chkAdd()")
public void check() throws Exception {
//throw new RuntimeException("出错退出");
throw new MyException("出错退出");
}
}
@Component
public class UserDao
{
public void addUser(String name) {
System.out.println("addUser");
}
}
public class ChkTest
{
public static void main(String[] args)
{
ApplicationContext factory = new ClassPathXmlApplicationContext("check.xml");
UserDao dao = (UserDao)factory.getBean("userDao");
try{
dao.addUser("");
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
写给后面遇到同样问题的人看的。
我也遇到这种情况,我在aop的before中做了自定义参数校验,抛出自定义异常。测试时虽然打印了我在全局异常处理中的内容,但返回给前端的是普通的Exception系统异常,且控制台也多余地打印了Exception异常。
解决方法是,对于做切面的方法(如controller中要做入参校验的类),做异常捕获。如,方法后添加throw MyException。这样idea会报is never thrown的警告,但实际上是用上了的。
public int say() throws Exception{
System.out.println("hello world!");
throw new MyException("退出错误");
}
public static void main(String[] args) throws Exception {
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
LogTestService service = (LogTestService)act.getBean("LogTestService");
try {
service.say();
} catch (Exception e) {
System.out.println("错误信息:" + e.getMessage());
}
}
<aop:config>
<aop:aspect ref="logManager">
<aop:pointcut id="logAOP" expression="execution(* com.study.spring.aop.service.impl.LogTestServiceImpl.say())"/>
<aop:after method="printLog" pointcut-ref="logAOP"/>
</aop:aspect>
</aop:config>