展示如何仅一次就完全记录异常和如何处理错误,其中可以通过将用户定 向到正确的信息(其中包括相关数据)以改进和加快用户问题的解决。最好的地 方是,该策略不需要附加到模式密集的框架中:它使用自定义应用程序代码或您 喜爱的第三方库代码。
端到端异常处理
第一个方面,如清单 4 所示,负责将数据访问和服务异常从模型(业务逻辑 )层转换为有意义的异常,并负责捕获有关当前代码正在做什么的上下文信息:
清单 4. 转换模型内的异常
/** Error handling for methods within the model */
aspect ModelErrorConversion {
/** execution of any method in the model */
pointcut modelExec() :
execution(* model..*(..));
// convert exception types
after() throwing (HibernateException e): modelExec() {
convertException(e, thisJoinPoint);
}
after() throwing (ServiceException e): modelExec() {
convertException(e, thisJoinPoint);
}
after() throwing (SOAPException e): modelExec() {
convertException(e, thisJoinPoint);
}
after() throwing (SOAPFaultException e): modelExec() {
convertException(e, thisJoinPoint);
}
// soften the checked exceptions
declare soft: ServiceException: modelExec();
declare soft: SOAPException: modelExec();
/** Converts exceptions to model exceptions, storing context */
private void convertException(Exception e, JoinPoint jp) {
ModelException me = new ModelException(e);
me.setCurrent (jp.getThis());
me.setArgs(jp.getArgs());
// ModelException extends RuntimeException, so this is unchecked
throw me;
}
}
AOP@Work: 使用方面的下几个步骤-学习建议之后(11)
时间:2011-09-07 IBM Ron Bodkin
ModelErrorConversion 方面确保当退出模型包中任何类的方法时, Hibernate 持久化引擎抛出的异常或来自 JAX RPC 调用的异常转换为特定类型的运行时异 常 。它还确保 SOAP 异常被软化:即从必须在 Java 代码中声明或捕获的已检查异 常转换为不需要这样做的运行时异常。该错误处理逻辑还捕获异常的上下文信息 :正在执行的对象和传递给方法的参数。我基于此构建了另一个对象,在从外部 调用模型时执行错误处理,如清单 5 所示:
清单 5. 进入模型时处理异常
/** Error handling for calls from outside into the model */
aspect ModelErrorHandling {
/** Entries to the model: calls from outside */
pointcut modelEntry() :
call(* model..* (..)) && !within(model..*);
/**
* Record information about requests that entered the model from outside
* where an object called them
**/
after(Object caller) throwing (ModelException e) :
modelEntry() && this(caller) {
handleModelError(e, caller, thisJoinPointStaticPart);
}
/**
* Record information about requests that entered the model from outside
* where no object was in context when they were called, e.g., in a
* static method
*/
after() throwing (ModelException e) :
modelEntry() && !this(*) {
handleModelError(e, null, thisJoinPointStaticPart);
}
private void handleModelError(ModelException e, Object caller, StaticPart staticPart) {
if (e.getInitialMethod() == null) {
e.setInitialCaller(calle
|