Leo
Leo

Reputation: 1919

is it possible to change or to wrap the exception when using Validate.notNull()

I am talking about the Validate API in apache commons lang, I do not see anything in the documentation

I know the the following is possible

try { Validate.notNull(object) } catch (NullPointerException ex) { throw MyCustomException(ex) }

but I was looking for something more simple then the whole try/catch block.

Upvotes: 2

Views: 1717

Answers (2)

Leo
Leo

Reputation: 1919

after some time of research we can conclude It is not possible.

Upvotes: 1

HereAndBeyond
HereAndBeyond

Reputation: 1454

  1. You can write something like that:
Validate.notNull(data, "Data cannot be null");

But you will be getting only NullPointerException with your message. This have been described here (at the top of article): http://commons.apache.org/proper/commons-lang/javadocs/api-3.9/org/apache/commons/lang3/Validate.html

An invalid null argument causes a NullPointerException.

There is no more simpler way.

  1. Or you can use Optional. e.g.:
        Optional<UserEntity> userOptional = userService.findByUsername(username);
        userOptional.orElseThrow(() -> new UsernameNotFoundException("No user found with username " + username));

Upvotes: 3

Related Questions