[英]How do i handle or log exception for Method references?
I have the code snippet below.我有下面的代码片段。 But i was wondering how to try catch exception with method references.但我想知道如何尝试使用方法引用捕获异常。 I want to write try catch block for getUserByUserId method, probably log it and catch with NotFoundException.我想为 getUserByUserId 方法编写 try catch 块,可能会记录它并使用 NotFoundException 捕获。 How do i refactor this code in case of method reference userService::getUserByUserId?在方法引用 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());
Leave the stream like that add the logic you want in the getUserByUserId
method.保留 stream 就像在getUserByUserId
方法中添加您想要的逻辑。 If it doesn't find a user it logs the error and throws the exception.如果它没有找到用户,它会记录错误并抛出异常。
EDIT: since you can't modify the method, you can do the following:编辑:由于您无法修改该方法,您可以执行以下操作:
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());
If it's unchecked exception, you don't need to do anything.如果是未经检查的异常,则无需执行任何操作。 But if its checked exception then you can do something like this:但是如果它的检查异常那么你可以做这样的事情:
..
.map((userService) -> {
try{
...//call userService#getUserByUserId
}catch(NotFoundException e){
//log or do something else
}
}) ...
You could write a mapper function in the class you are doing the chaining of calls:您可以在 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();
}
}
And use it like this:并像这样使用它:
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.