Mohamed Said Benmousa
Mohamed Said Benmousa

Reputation: 499

How can I throw my own custom message in @NonNull exception using lombok?

I started using lombok project, and I had a doubt. Let's supose I have a method with one argument method(@NonNull arg). If I call that method with null argument method(null), I will get the following exception: java.lang.NullPointerException: arg.

But let's supose I want that exception message says something like arg cannot be null instead of the other one (regardless of the sense of that message, I only want to know how to cusomize the exception message using @NonNull annotation).

Thanks!

Upvotes: 8

Views: 13430

Answers (3)

Roel Spilker
Roel Spilker

Reputation: 34462

You can't.

However, you can configure lombok to throw an IllegalArgumentException instead. That will have the message arg is null.

To configure this, add lombok.nonNull.exceptionType = IllegalArgumentException to your lombok.config file.

Disclosure: I am a lombok developer.

Upvotes: 12

Paul Lemarchand
Paul Lemarchand

Reputation: 2096

According to Lombok's documentation, the @NonNull annotation just adds an if statement at the top of your function to check if its null. So if you don't want to use any other library, you could just do it yourself :

class NullArgumentException extends IllegalArgumentException {

    public NullArgumentException() {
        super("arg cannot be null");
    }
}

public class Test {

    public static void main(String[] args) {

        try {
            foo(null);
        } catch(IllegalArgumentException e) {
            // or System.out.println(e.getMessage())
            e.printStackTrace();
        }
    }

    public static void foo(Integer i) throws IllegalArgumentException {
        if(i == null) throw new NullArgumentException();
    }
}

Upvotes: 0

Kysil Ivan
Kysil Ivan

Reputation: 1037

Lombok @NonNull do not allow this.
Try using @NotNull(message = "arg cannot be null") from javax.validation.constraints package.

Upvotes: 2

Related Questions