我正在使用一个涉及 Web 层中的 Struts2 和业务层中的 Spring 的应用程序。我还有 BusinessException 类,所有业务服务都将使用它来创建与业务相关的验证失败,这些验证失败必须上升到 Web 层,并应作为验证消息显示给用户。我可以通过在我的 Action 类中编写来轻松地做到这一点:
ClientAction extends ActionSupport throws Exception{
....
try{
clientService.searchClient();
}catch(InvalidClientSearchCriteriaException e){
addActionMessage("Invlid Search Criteria");
}
...
每个动作类中都有类似的代码。但是我不想用 try catch 块污染我的动作类。相反,如果我可以在一个地方编写 try catch 块并将那里的所有异常作为 BusinessExceptions 捕获并从这些异常中的嵌入消息/错误创建消息/错误,那会更好。我能想到的一种方法是使用拦截器或预结果监听器。但是我不能使用像下面这样的拦截器来捕获从动作类抛出的 BusinessExceptions ......
ExceptionInterceptor extends AbstractInterceptor(ActionInvocation ivocation,...){
try{
invocation.invoke();
}catch(Exception e){
if(e instanceof BusinessException){
ActionSupport as = (ActionSupport)invocation.getAction();
String message = extractMessagefromException()//--custom method to extract message embedded in exception.
as.addActionMessages(message);
//-- above will not work result has already been rendered right? and hence it wouldn't matter if i add action messages now.
}
}
}
使用预结果监听器的第二种方法是像上面一样在预结果监听器的方法中添加动作消息,因为结果尚未呈现,我可以安全地更改它。但是我不确定预结果监听器是否会执行,如果在操作中引发异常?即使是这样,我怎样才能得到动作抛出的异常对象?
请让我知道我不必用 try-catch 块弄乱我的课程的任何其他方法