{"record":{"id":"2c5fd0f36864fb85","repo":"sqshq/piggymetrics","slug":"user-already-exists-it-getusername","errorCode":null,"errorMessage":"user already exists: + it.getUsername()","messagePattern":"user already exists: \\+ it\\.getUsername\\(\\)","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"auth-service/src/main/java/com/piggymetrics/auth/service/UserServiceImpl.java","lineNumber":28,"sourceCode":"import org.springframework.util.Assert;\n\nimport java.util.Optional;\n\n@Service\npublic class UserServiceImpl implements UserService {\n\n\tprivate final Logger log = LoggerFactory.getLogger(getClass());\n\n\tprivate static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();\n\n\t@Autowired\n\tprivate UserRepository repository;\n\n\t@Override\n\tpublic void create(User user) {\n\n\t\tOptional<User> existing = repository.findById(user.getUsername());\n\t\texisting.ifPresent(it-> {throw new IllegalArgumentException(\"user already exists: \" + it.getUsername());});\n\n\t\tString hash = encoder.encode(user.getPassword());\n\t\tuser.setPassword(hash);\n\n\t\trepository.save(user);\n\n\t\tlog.info(\"new user has been created: {}\", user.getUsername());\n\t}\n}\n","sourceCodeStart":10,"sourceCodeEnd":38,"githubUrl":"https://github.com/sqshq/piggymetrics/blob/6bb2cf9ddbca980b664d3edbb6ff775d75369278/auth-service/src/main/java/com/piggymetrics/auth/service/UserServiceImpl.java#L10-L38","documentation":"UserServiceImpl.create() checks UserRepository for an existing user with the same username before saving. If repository.findById(user.getUsername()) returns a present Optional, it throws IllegalArgumentException with the conflicting username. This is an application-level uniqueness guard for the user entity's primary key, thrown before any password hashing or persistence occurs.","triggerScenarios":"Calling create(User) with a user whose getUsername() matches a user already persisted in the repository (e.g., POST /users with a username that was previously registered, or retrying a registration request that already succeeded).","commonSituations":"Duplicate registration attempts from a double-clicked signup form or retried HTTP request without idempotency handling; a microservice (e.g., account-service) provisioning a user that already exists in auth-service's database; test fixtures or seed data re-run against a persistent database; missing a pre-check like repository.findById(username).isPresent() on the client side before invoking create().","solutions":["Check existence before creating: if (repository.findById(user.getUsername()).isPresent()) { handle already-registered path (return, or surface a friendly 'username taken' response) }","Catch IllegalArgumentException around the create() call and map it to an HTTP 409 Conflict response instead of a 500.","If the user should be upserted, replace the guard with repository.save(user) directly (or findById(...).map(update).orElseGet(create)).","Ensure callers use idempotency keys or check the account-service side so retried registrations don't re-enter create()."],"exampleFix":"// before\nOptional<User> existing = repository.findById(user.getUsername());\nexisting.ifPresent(it -> { throw new IllegalArgumentException(\"user already exists: \" + it.getUsername()); });\n\n// after\nif (repository.findById(user.getUsername()).isPresent()) {\n    throw new UserExistsException(user.getUsername()); // map to 409 Conflict in the controller/@ControllerAdvice\n}\n// or, for idempotent upsert semantics:\n// repository.save(user);","handlingStrategy":"try-catch","validationCode":"// caller-side pre-check before invoking create()\nif (userRepository.findById(user.getUsername()).isPresent()) {\n    // username already taken — return 409 Conflict or merge instead of creating\n    return;\n}","typeGuard":"// Java: Optional-based narrowing\nOptional<User> existing = repository.findById(user.getUsername());\nif (existing.isPresent()) {\n    User conflict = existing.get(); // safely narrowed, no exception path\n    return;\n}","tryCatchPattern":"try {\n    userService.create(user);\n} catch (IllegalArgumentException e) {\n    // duplicate username\n    return ResponseEntity.status(HttpStatus.CONFLICT).body(\"username already exists\");\n}","preventionTips":["Always check repository.findById(username) before calling create() for new registrations.","Return HTTP 409 Conflict (not 500) when the username is taken, via a @ControllerAdvice mapping IllegalArgumentException.","Make client registration flows idempotent: treat 'already exists' as success-or-conflict rather than retrying blindly.","Consider a custom exception (e.g., UserExistsException) instead of IllegalArgumentException so duplicate-vs-bug can be distinguished by callers.","Back the username with a database unique constraint so race conditions between check and save are also caught."],"tags":["duplicate-record","uniqueness-constraint","spring","jpa","user-registration"],"backgroundTag":"file-already-exists","analyzedSha":"6bb2cf9ddbca980b664d3edbb6ff775d75369278","analyzedAt":"2026-09-07T14:43:40.747Z","contentChangedAt":"2026-09-07T14:43:40.747Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}