我有下面的代码片段。但我想知道如何尝试用方法引用捕获异常。我想为getUserByUserId方法编写try-catch块,可能会记录它并使用NotFoundException捕获。如果方法引用userService::getUserByUserId,我该如何重构此代码?
List<String> listofIds= ldapUsers.stream()
.map(PersonDTO::getUserId)
.map(userService::getUserByUserId)
.filter(Optional::isPresent)
.map(Optional::get)
.map(User::get_id)
.collect(Collectors.toList());
您可以在进行调用链接的类中编写一个映射器函数:
private Optional<User> getUser(PersonDTO personDTO) {
try {
return userService.getUserByUserId(personDTO.getUserId());
} catch (Exception ex) {
log.error("Your message here", ex);
throw new NotFoundException();
}
}
并像这样使用:
List<String> listofIds = ldapUsers.stream()
.map(PersonDTO::getUserId)
.map(this::getUser)
.filter(Optional::isPresent)
.map(Optional::get)
.map(User::get_id)
.collect(Collectors.toList());
这样保留流,以便在getUserByUserId
方法中添加所需的逻辑。如果没有找到用户,它会记录错误并抛出异常。
编辑:由于您无法修改方法,您可以执行以下操作:
List<String> listofIds= ldapUsers.stream()
.map(PersonDTO::getUserId)
.map(userId -> {
User user = userService.getUserByUserId(userId);
if(user == null) {
log.error("User not found");
throw new NotFoundException();
}
return user;
})
.filter(Optional::isPresent)
.map(Optional::get)
.map(User::get_id)
.collect(Collectors.toList());
如果是未检查的异常,则无需执行任何操作。但如果它检查了异常,那么你可以这样做:
..
.map((userService) -> {
try{
...//call userService#getUserByUserId
}catch(NotFoundException e){
//log or do something else
}
}) ...