jcabi-aspects

repository·master·Indexed 19 days ago

https://github.com/jcabi/jcabi-aspects

A collection of Aspect-Oriented Programming (AOP) aspects for Java that allow developers to add behaviors such as retries and logging via annotations. Key features include the @RetryOnFailure annotation for automatic retry logic and the @UnitedThrow annotation to restrict or encapsulate exceptions during method execution.

Tokens
508
Snippets
3
Records
4
Agent score
18%

What's inside jcabi-aspects

  1. Overview of jcabi-aspects

    master
    jcabi-aspects is a collection of Aspect-Oriented Programming (AOP) aspects for Java. It allows you to modify application behavior—such as adding retry logic or logging—by using annotations instead of writing manual boilerplate code. This promotes cleaner code by separating cross-cutting concerns from business logic.
  2. Use @RetryOnFailure to implement retry logic

    master

    Instead of manually implementing do/while loops for error handling, you can annotate a method with @RetryOnFailure. The AOP aspect will automatically handle retrying the method execution in the event of a failure.

    import com.jcabi.aspects.RetryOnFailure;
    
    public class MyResource {
        @RetryOnFailure
        public String load(final URL url) {
            return url.openConnection().getContent();
        }
    }
  3. Use the @UnitedThrow annotation to restrict allowed exceptions

    master

    The @UnitedThrow annotation is used to specify which exceptions are permitted to propagate during the execution of an aspect-advised method. Any exception thrown during execution that is not the specified type (or a subclass of it) will be encapsulated.

    By default, if no value is provided, all exceptions are encapsulated because the default value is UnitedThrow.None.

    @UnitedThrow(MyAllowedException.class)
    public void myMethod() throws MyAllowedException {
        // ...
    }
  4. Use UnitedThrow.None to encapsulate all exceptions

    master

    The UnitedThrow.None class is a special Throwable used as the default value for the @UnitedThrow annotation. When @UnitedThrow is applied without arguments, it effectively instructs the aspect to encapsulate all exceptions, as no specific exception type is marked as 'allowed'.

    @UnitedThrow // Defaults to UnitedThrow.None.class
    public void myMethod() {
        // ...
    }