代码之家  ›  专栏  ›  技术社区  ›  Georgi Michev

如何在可选类中自定义NoSuchelementException的错误消息

  •  1
  • Georgi Michev  · 技术社区  · 6 年前

    我有个方法 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.");
        }
    }
    

    我发现这是不需要的,因为 java.util.Optional 使用类。在Oracle文档中,我发现 get() 被使用,然后就没有价值了 NoSuchElementException 被抛出。将错误消息添加到异常中的最佳方法是什么?我正试图打开 Optional Eclipse中的类尝试在其内部进行更改(不确定这是否是好的实践),但Eclipse不允许我访问这个类,另一方面,我读到这个类也是最终的。

    3 回复  |  直到 6 年前
        1
  •  3
  •   Peter Walser    6 年前

    当解决 Optional value ,您可以直接

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

    StatementBundle bundle = statementBundleRepository.findById(bundleId)
        .orElseThrow(()
         -> new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");
    
        2
  •  1
  •   L.Spillner    6 年前

    Optional orElseThrow(...) Supplier

    StatementBundle bundle = bundleOpt.orElseThrow( ()->new NotFoundException("Statement bundle with id: " + bundleId + " is not found.") );
    
        3
  •  0
  •   user9455968    6 年前

    NoSuchElementException

    try {
        try {
            // We simulate a failing .get() on an Optional.
            throw new NoSuchElementException("message from Optional.get()");
        } catch (NoSuchElementException ex) {
            // We wrap the exception into a custom exception and throw this.
            throw new MyException("my message", ex);
        }
    } catch (MyException ex) {
        // Now we catch the custom exception and can inspect it and the
        // exception that caused it.
        System.err.println(ex.getClass().getCanonicalName()
                + ": " + ex.getMessage()
                + ": " + ex.getCause().getMessage());
    }
    

    MyException: my message: message from Optional.get()