使用异常处理注解? [英] Using annotations for exception handling?

查看:148
本文介绍了使用异常处理注解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有抛出​​某种异常的方法。唯一的例外投掷code在于,访问外部服务的第三方库。我有几类,做的工作的一个很好的协议与外部服务并没有异常处理在整个应对潜在的问题很多。我打的问题是,我可能有很多例外,但我可能只需要执行一些操作之一,如果有一个,还有胡椒一吨左右的try / catch块。的类型的异常可能甚至不相关的,或不同的方法可能抛出同一类型的异常,但不同的操作需要取决于方法抛它要采取

Let's say I have a method that throws an Exception of some kind. The exception-throwing code lies in a third-party library that access an external service. I have a few classes that do a good deal of work with external services and there is a LOT of exception handling throughout to deal with potential problems. The issue I'm hitting is that I may have a lot of exceptions, but I may only need to perform one of a few actions if there is one, and there are a ton of try/catch blocks peppered about. The type of exception may not even be relevant, or different methods may throw the same type of exception, but different actions need to be taken depending on the method throwing it.

我正在寻找的是能够取代try / catch语句,只是规定时存在这样的方法异常时采取的行为的注释。我知道,春天ApsectJ可以做这样的事情,但我目前还无法轻松地添加任何新的依赖或修改POM以调整现有的。因此,我希望这可以用自定义的注解来完成。例如:

What I'm looking for is an annotation that can supplant try/catch and simply dictate the behavior to be taken when there is an exception in that method. I know that Spring ApsectJ can do this sort of thing, but I'm not currently able to easily add any new dependencies or modify the pom to adjust existing ones. As such, I'm hoping that this can be accomplished with a custom annotation. For example:

@Catcher(action=SomeEnum.SOME_ACTION)
public void doSomething(ServiceObj obj) throws SomeException {
    ExternalService.makeThingsHappen(obj);
}

我想presume一个单独的类会处理异常,当然。另外一个困难是,我需要传递,以及在ServiceObj。如果makeThingsHappen()失败,我可能需要OBJ执行其他操作。操作变量将告诉处理程序类做什么用的obj。

I would presume that a separate class would handle exceptions, of course. An additional difficulty is that I would need the ServiceObj that is passed as well. If makeThingsHappen() fails, I may need obj to perform additional actions. The action variable will tell the handler class what to do with obj.

可以这样无严重muckery做的,还是我希望的东西可能不存在?

Can this be done without severe muckery, or am I hoping for something that may not exist?

推荐答案

这应该是一个低层次的过程,它并不意味着我们不能有目前的水平同样的事情,但可能需要一堆$的C $ c和复杂的将系统中的一点。
不过我的建议是这样的(我希望我得到了正确的),首先定义谁愿意来处理异常的接口,这样的事情。

This should be a low-level process, and it doesn't mean we cannot have the same thing with current level, but it may needs a bunch of code and would complex the system a little. However my suggestion would be like this(I hope I got it correct), first define an interface for who wants to process exceptions, something like this.

interface ExceptionHandler{
  void handleException(Throwable t);
}

然后提供用户(API)的标注来标记它的方法可能会抛出一些异常。

then provide an annotation for user(API) to mark its methods may throws some exception.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
@interface Catch{
  public Class<? extends ExceptionHandler> targetCatchHandler();
  public Class<? extends Throwable> targetException() default Exception.class;
}


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface CatchGroup{
  public Catch[] catchers();
}

接下来我们需要一个接口来开始这样调用这可能会抛出异常的方法,什么的。

next we need a interface to start to call the method which may throws exception, something like this.

interface Caller{
  void callMethod()throws Throwable;
}

那么你需要谁照顾和管理的执行流程,并调用可能异常处理一个人

then you need a guy who take care and manage the flow of the execution and call the possible exception handler

class MethodCaller{
  /*
   * @param isntance: instance which implemented the Caller interface
   */
  public static void callMethod(Caller instance)
      throws Exception {
    Method m = instance.getClass().getMethod("callMethod");
    Annotation as[] = m.getAnnotations();
    Catch[] li = null;
    for (Annotation a : as) {
      if (a.annotationType().equals(CatchGroup.class)) {
        li = ((CatchGroup) a).catchers();
      }
      // for(Catch cx:li){cx.targetException().getName();}
    }
    try {
      instance.callMethod();
    } catch (Throwable e) {
      Class<?> ec = e.getClass();
      if (li == null) {
        return;
      }
      for (Catch cx : li) {
        if (cx.targetException().equals(ec)) {
          ExceptionHandler h = cx.targetCatchHandler().newInstance();
          h.handleException(e);
          break;
        }
      }
    }
  }
}

最后,让我们有一些例子,它工作得很好对我来说,这很酷。
异常处理程序。

and finally, lets have some example, it works very well for me, it's cool. the exception handler.

public class Bar implements ExceptionHandler{//the class who handles the exception
  @Override
  public void handleException(Throwable t) {
    System.out.println("Ta Ta");
    System.out.println(t.getMessage());
  }
}

和方法呼叫者

class Foo implements Caller{//the class who calls the method
  @Override
  @CatchGroup(catchers={ 
      @Catch(targetCatchHandler=Bar.class,targetException=ArithmeticException.class),
      @Catch(targetCatchHandler=Bar.class,targetException=NullPointerException.class)})
  public void callMethod()throws Throwable {
    int a=0,b=10;
    System.out.println(b/a);
  }
  public static void main(String[] args) throws Exception {
    Foo foo=new Foo();
    MethodCaller.callMethod(foo);
  }
}

如你所见,用户必须调用由 callmethod 方法()的方法,你也省略来电接口,使​​用注释来声明一个类以上的方法,它需要一堆额外的codeZ。
我希望我可以给一些手。

as you see, the user HAS TO call the methods by the callmethod() method, you would also omit the Caller interface, and use annotation to declare more than one method in a class that it needs a bunch of extra codez. I hope I could give some hand.

这篇关于使用异常处理注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆