如何在Optional类中自定义NoSuchElementException的错误消息

Geo*_*hev 4 java option-type

NotFoundException我有一个方法,如果我的对象 id 是 则抛出null

public void removeStatementBundleService(String bundleId) throws NotFoundException {
    Optional<StatementBundle> bundleOpt = statementBundleRepository.findById(bundleId);

    if(bundleOpt.isPresent()) {
        StatementBundle bundle = bundleOpt.get();

        if(bundle.getStatements() != null && !bundle.getStatements().isEmpty()) {               
            for(Statement statement: bundle.getStatements()) {
                statementRepository.delete(statement);
            }
        }

        if(bundle.getFileId() != null) {
            try {
                fileService.delete(bundle.getFileId());
            } catch (IOException e) {
                e.printStackTrace();
            }   
        }

        statementBundleRepository.delete(bundle);

    } else {
        throw new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现由于java.util.Optional使用了该类,所以不需要这样做。在oracle文档中我发现get()使用了if并且没有值然后NoSuchElementException抛出。将错误消息添加到异常的最佳方法是什么?我试图Optional在 Eclipse 中打开该类以尝试在其中进行更改(不确定这是否是好的做法),但 Eclipse 不会让我访问该类,另一方面我读到该类也是最终的。

Pet*_*ser 6

解析时Optional value,如果值不存在,可以直接抛出异常

Optional<StatementBundle> bundleOpt = statementBundleRepository.findById(bundleId);
StatementBundle bundle = bundleOpt.orElseThrow(() 
    -> new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");
Run Code Online (Sandbox Code Playgroud)

或(单个语句):

StatementBundle bundle = statementBundleRepository.findById(bundleId)
    .orElseThrow(()
     -> new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");
Run Code Online (Sandbox Code Playgroud)