跟进这个comment我之前的问题。我试图从 @Around
建议中抛出异常,并在被调用者类和/或方法中捕获它。但是我收到了这个错误:
Stacktraces
java.lang.Exception: User not authorized
com.company.aspect.AuthorizeUserAspect.isAuthorized(AuthorizeUserAspect.java:77)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:616)
...
Aspect 代码是:
@Aspect
public class AuthorizeUserAspect {
@AuthoWired
private UserService service;
@Pointcut("@annotation(module)")
public void authorizeBeforeExecution(AuthorizeUser module) {}
@Around(value = "authorizeBeforeExecution(module)", argNames="module")
public Object isAuthorized(ProceddingJoinPoint jp, AuthorizeUser module) throws Throwable {
// Check if the user has permission or not
service.checkUser();
if ( /* User has NOT permission */ ) {
throw new MyCustomException("User not authorized"); // => this is line 77
}
return jp.proceed();
}
}
基于 Struts 的 UI 操作代码是:
@Component
public class DashboardAction extends ActionSupport {
@Override
@AuthorizeUser
public String execute() {
...
}
private void showAccessDenied() {
...
}
}
问题是我如何或在何处捕获该异常以执行 showAccessDenied()
?
最佳答案
要处理未捕获的异常,如 MyCustomException
,您需要在 Struts 2 中定义一个全局异常处理程序。请查看本指南:http://struts.apache.org/2.3.4.1/docs/exception-handling.html
关于java - 如何捕获从@Around 抛出的连接点中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12277944/