使用 Validate.notNull() 时是否可以更改或包装异常

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

我说的是验证 API 在 apache commons lang 中,我在 documentation

中没有看到任何内容

我知道以下是可能的

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

但我一直在寻找比整个 try/catch 块更简单的东西。

  1. 你可以这样写:
Validate.notNull(data, "Data cannot be null");

但是您的消息只会收到 NullPointerException。这已在此处(在文章顶部)进行了描述:http://commons.apache.org/proper/commons-lang/javadocs/api-3.9/org/apache/commons/lang3/Validate.html

An invalid null argument causes a NullPointerException.

没有比这更简单的方法了。

  1. 或者您可以使用可选的。例如:
        Optional<UserEntity> userOptional = userService.findByUsername(username);
        userOptional.orElseThrow(() -> new UsernameNotFoundException("No user found with username " + username));

经过一段时间的研究,我们得出结论这是不可能的。