refactor: throw proper error on registration conflict, handle properly
This commit is contained in:
parent
46e52e20cc
commit
b4351ceaea
4 changed files with 93 additions and 45 deletions
|
@ -2,6 +2,7 @@ package de.szut.casino.exceptionHandling;
|
|||
|
||||
import de.szut.casino.exceptionHandling.exceptions.InsufficientFundsException;
|
||||
import de.szut.casino.exceptionHandling.exceptions.UserNotFoundException;
|
||||
import jakarta.persistence.EntityExistsException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
|
@ -24,4 +25,10 @@ public class GlobalExceptionHandler {
|
|||
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
|
||||
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(EntityExistsException.class)
|
||||
public ResponseEntity<?> handleEntityExistsException(EntityExistsException ex, WebRequest request) {
|
||||
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
|
||||
return new ResponseEntity<>(errorDetails, HttpStatus.CONFLICT);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package de.szut.casino.user;
|
||||
|
||||
import de.szut.casino.user.dto.CreateUserDto;
|
||||
import jakarta.persistence.EntityExistsException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
@ -19,11 +20,11 @@ public class UserService {
|
|||
|
||||
public UserEntity createUser(CreateUserDto createUserDto) {
|
||||
if (userRepository.existsByUsername(createUserDto.getUsername())) {
|
||||
throw new IllegalArgumentException("Username is already taken");
|
||||
throw new EntityExistsException("Username is already taken");
|
||||
}
|
||||
|
||||
if (userRepository.existsByEmail(createUserDto.getEmail())) {
|
||||
throw new IllegalArgumentException("Email is already in use");
|
||||
throw new EntityExistsException("Email is already in use");
|
||||
}
|
||||
|
||||
UserEntity user = new UserEntity(
|
||||
|
|
Reference in a new issue