Skip to content

Commit 6d635b4

Browse files
Added use of 'orElseThrow()' to handle 'Optional'
1 parent 0781cca commit 6d635b4

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

src/main/java/hexlet/code/component/DataInitializer.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import hexlet.code.dto.task.TaskCreateDTO;
55
import hexlet.code.dto.taskStatus.TaskStatusCreateDTO;
66
import hexlet.code.dto.user.UserCreateDTO;
7+
import hexlet.code.exception.ResourceNotFoundException;
78
import hexlet.code.repository.UserRepository;
89
import hexlet.code.service.LabelService;
910
import hexlet.code.service.TaskService;
@@ -58,7 +59,8 @@ public void run(ApplicationArguments args) throws Exception {
5859
});
5960

6061
// Task
61-
var user = userRepository.findByEmail(email).get();
62+
var user = userRepository.findByEmail(email)
63+
.orElseThrow(() -> new ResourceNotFoundException("User with email " + email + " not found"));
6264

6365
taskStatusData.values().forEach(v ->
6466
IntStream.range(1, 5).forEach(i -> {

src/main/java/hexlet/code/util/UserUtils.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,14 @@ public User getCurrentUser() {
2121

2222
var email = authentication.getName();
2323

24-
return userRepository.findByEmail(email).get();
24+
return userRepository.findByEmail(email)
25+
.orElseThrow(() -> new ResourceNotFoundException("User with email " + email + " not found"));
2526
}
2627

2728
public boolean isCurrentUser(long id) {
28-
var userEmail = userRepository.findById(id).get().getEmail();
29+
var userEmail = userRepository.findById(id)
30+
.orElseThrow(() -> new ResourceNotFoundException("User with id " + id + " not found"))
31+
.getEmail();
2932
var authentication = SecurityContextHolder.getContext().getAuthentication();
3033

3134
return userEmail.equals(authentication.getName());

0 commit comments

Comments
 (0)