简体   繁体   English

Return.map lambda 和抛出异常的 function

[英]Return .map lambda with function that throws exception

Is there any way to use mapping optional entity as shown below when the function called in lambda throws an exception and when it does I want to pass this exception to function that called getFieldHives in first place, IDE force me to wrap it in try/catch block and when trying to throw it again i end up with loop of try/catch. Is there any way to use mapping optional entity as shown below when the function called in lambda throws an exception and when it does I want to pass this exception to function that called getFieldHives in first place, IDE force me to wrap it in try/catch块,当试图再次抛出它时,我最终会出现 try/catch 循环。 Or perhaps there is other way of approaching this issue, my main goal is to avoid using optionalFieldDAO.isPresent() and optionalFieldDAO.get().或者也许有其他方法可以解决这个问题,我的主要目标是避免使用 optionalFieldDAO.isPresent() 和 optionalFieldDAO.get()。

public List<HiveResponse> getFieldHives(String token, Long id) throws UserNotFoundException, FieldNotFoundException {
Optional<FieldDAO> optionalFieldDAO = fieldRepository.findById(id);

        return optionalFieldDAO
                .map(fieldDAO -> createFieldHivesResponse(fieldDAO, user))
                .orElseThrow(() -> new FieldNotFoundException("Field not found!"));
}

private List<HiveResponse> createFieldHivesResponse(FieldDAO fieldDAO, UserDAO user) throws FieldNotOwnedException {
        if(!user.getFieldDAOList().contains(fieldDAO)) throw new FieldNotOwnedException("Field not owned!");
        
        //rest of code
    }

Optional field can contain empty value(in case of null) or value.可选字段可以包含空值(如果为空)或值。 but your method return type is list.但是您的方法返回类型是列表。 so you need to collect values in a list所以你需要在列表中收集值

    public List<HiveResponse> getFieldHives(String token, Long id) throws UserNotFoundException, FieldNotFoundException {
Optional<FieldDAO> optionalFieldDAO = fieldRepository.findById(id);
        List<HiveResponse> hiveResponses = new ArrayList<>();
        optionalFieldDAO.ifPresent(dao-> {
            hiveResponses.addAll(createFieldHivesResponse(dao,user));
        });
        return hiveResponses;
}

private List<HiveResponse> createFieldHivesResponse(FieldDAO fieldDAO, UserDAO user) throws FieldNotOwnedException {
        if(!user.getFieldDAOList().contains(fieldDAO)) throw new FieldNotOwnedException("Field not owned!");
        
        //rest of code
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM