Skip to content

Commit

Permalink
✨ feat(UsersService.java): Add UsernameNotFoundException for bett…
Browse files Browse the repository at this point in the history
…er security exception handling.
  • Loading branch information
vnobo committed Dec 18, 2024
1 parent 32c614e commit 6ecb7d9
Showing 1 changed file with 6 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
Expand Down Expand Up @@ -92,7 +93,7 @@ public Mono<User> add(UserRequest request) {
return this.usersRepository.existsByUsernameIgnoreCase(request.getUsername()).flatMap(exists -> {
if (exists) {
return Mono.error(RestServerException.withMsg("User already exists",
"Username [" + request.getUsername() + "] already exists!"));
new UsernameNotFoundException("User by username [" + request.getUsername() + "] already exists")));
}
return this.operate(request);
});
Expand All @@ -111,9 +112,10 @@ public Mono<User> add(UserRequest request) {
* @return A Mono that, when subscribed to, emits the updated User entity after modification or throws an exception if the user was not found.
*/
public Mono<User> modify(UserRequest request) {
return this.usersRepository.findByUsername(request.getUsername())
.switchIfEmpty(Mono.error(RestServerException.withMsg(
"User not found!", "User by username [" + request.getUsername() + "] not found!")))
Mono<User> userFoundMono = Mono.defer(() -> Mono.error(RestServerException
.withMsg("User [" + request.getUsername() + "] not found",
new UsernameNotFoundException("User by username [" + request.getUsername() + "] not found!"))));
return this.usersRepository.findByUsername(request.getUsername()).switchIfEmpty(userFoundMono)
.flatMap(user -> {
request.setId(user.getId());
request.setCode(user.getCode());
Expand Down Expand Up @@ -172,8 +174,6 @@ public Mono<User> save(User user) {
} else {
assert user.getId() != null;
return this.usersRepository.findById(user.getId())
.switchIfEmpty(Mono.error(RestServerException.withMsg("User not found",
"User by id [" + user.getId() + "] not found!")))
.flatMap(old -> {
user.setCreatedTime(old.getCreatedTime());
user.setPassword(old.getPassword());
Expand Down

0 comments on commit 6ecb7d9

Please sign in to comment.