Class ThreadLocalReason

java.lang.Object
net.dv8tion.jda.api.audit.ThreadLocalReason

public final class ThreadLocalReason extends Object
Thread-Local audit-log reason used automatically by AuditableRestAction instances when no other reason was set.

Note that RestAction.queue() will forward any thread-local reason set through this handle. Thus audit-log reasons done by callbacks will also use the one set from the executing thread.

Example without closable


 String previousReason = ThreadLocalReason.getCurrent();
 ThreadLocalReason.setCurrent("Hello World");
 try {
     guild.ban(user, 0).queue(v -> {
         guild.unban(user).queue(); // also uses the reason "Hello World"
     });
 } finally {
     //Forwarding the reason is not async so resetting it here is fine.
     ThreadLocalReason.setCurrent(previousReason);
 }
 //This will not use the reason "Hello World" but the previous, or none if none was set previously
 guild.kick(user).queue();
 

Example with closable


 try (ThreadLocalReason.Closable __ = ThreadLocalReason.closable("Hello World")) {
     guild.ban(user, 0).queue(v -> {
         guild.unban(user).queue(); // also uses the reason "Hello World"
     });
 } // automatically changes reason back
 //This will not use the reason "Hello World" but the previous, or none if none was set previously
 guild.kick(user).queue();
 
See Also:
  • Method Details

    • setCurrent

      public static void setCurrent(@Nullable String reason)
      Sets the current reason that should be used for AuditableRestAction.
      Parameters:
      reason - The reason to use, or null to reset
    • resetCurrent

      public static void resetCurrent()
      Resets the currently set thread-local reason, if present.
    • getCurrent

      @Nullable public static String getCurrent()
      The current reason that should be used for AuditableRestAction.
      Returns:
      The current thread-local reason, or null
    • closable

      @Nonnull public static ThreadLocalReason.Closable closable(@Nullable String reason)
      Creates a new ThreadLocalReason.Closable instance.
      Allows to use try-with-resources blocks for setting reasons
      Parameters:
      reason - The reason to use
      Returns:
      The closable instance