HowToBasic 2
HowToBasic 2

Reputation: 23

ContextException: Unknown Ban can't be caught (Discord Java)

My unban command sometimes throws a ContextException, when you unban a person who wasn't banned. I wanted to catch it with a try catch block to notify the user that the person they are trying to unban isn't banned. This is what I tried:

try {
   event.getGuild().unban(event.getMessage().getContentRaw().substring(8)).queue();
} catch(ContextException e) {
   event.getChannel().sendMessage("This user isn't banned!").queue();
   return;
}

But the catch() line just says Exception 'net.dv8tion.jda.api.exceptions.ContextException' is never thrown in the corresponding try block.

Upvotes: 1

Views: 1057

Answers (2)

Minn
Minn

Reputation: 6131

Your exception, in this case isn't even a ContextException but an ErrorResponseException. Since queue(...) does asynchronous operations in a different thread, the exceptions cannot be thrown from here. Instead, you should use the failure callback as described by the documentation.

You can use ErrorHandler to handle specific ErrorResponses.

Example:

String userId = event.getMessage().getContentRaw().substring(8);
ErrorHandler handler = new ErrorHandler().handle(ErrorResponse.UNKNOWN_BAN, (error) -> {
    event.getChannel().sendMessage("This user isn't banned!").queue();
});

event.getGuild()
     .unban(userId)
     .queue(null, handler);

The ContextException is only there to tell you where in your code the error originated from. Since the actual exception happens on other threads which give you no context to find the issue.

Upvotes: 3

Hyeon Lee
Hyeon Lee

Reputation: 147

ContextException handles async exception. So your try block cannot catch the exception.
You can change your code like this.

event.getGuild().unban(event.getMessage().getContentRaw().substring(8)).queue(
    null,
    (error) -> {
        if (error.getMessage().equals("10026: Unknown Ban")) {
            event.getChannel().sendMessage("This user isn't banned!").queue();
        }
    }
);

Upvotes: 2

Related Questions