如何在 optional.orElseThrow(..) 中抛出异常之前执行操作

How to perform an operation before throwing an exception in optional.orElseThrow(..)

当前工作代码:

AppUser user = repository.findByEmail(userName);
                .orElseThrow(() -> new RuntimeException("User not found: " + userName));

需要像下面这样更改但它不起作用,出现编译错误:

AppUser user = repository.findByEmail(userName)
   .orElseThrow(() -> {
        AuditEvent event = 
                 new AuditEvent(userName, "AUTHENTICATION_FAILURE", new HashMap<String, Object>());
        auditPublisher.publish(event);
        new RuntimeException("User not found: " + userName);
});

虽然我已经为此做了类似下面的工作,但这似乎不是一个好的方法。如果可行,请提出更好的方法。

Optional<AppUser> userOptional = repository.findByEmail(userName);
AppUser user = userOptional.orElse(null);
if (user == null) {
    AuditEvent event = new AuditEvent(userName, "AUTHENTICATION_FAILURE", new HashMap<String, Object>());
    auditPublisher.publish(event);
    throw new RuntimeException("User not found: " + userName);

}

如果需要任何其他详细信息来澄清我的问题,请告诉我。

您的 lambda 中缺少 return 语句。

AppUser user = repository.findByEmail(userName)
   .orElseThrow(() -> {
        AuditEvent event = 
                 new AuditEvent(userName, "AUTHENTICATION_FAILURE", new HashMap<String, Object>());
        auditPublisher.publish(event);
        return new RuntimeException("User not found: " + userName);
});