[英]How do i handle or log exception for Method references?
我有下面的代码片段。 但我想知道如何尝试使用方法引用捕获异常。 我想为 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());
保留 stream 就像在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
}
}) ...
您可以在 class 中编写映射器 function 您正在执行调用链接:
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.