[M] Rename Controller & Excpetion Handler, merge Aspect to class.

This commit is contained in:
VergeDX
2021-01-21 10:03:56 +08:00
parent 3286c982aa
commit 85e286cc42
3 changed files with 7 additions and 36 deletions
@@ -11,7 +11,7 @@ import java.util.List;
import java.util.stream.Collectors;
@RestControllerAdvice
public class RegistryExceptionHandler {
public class CommonExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
// ConstraintViolationException will be wrapped to TransactionSystemException!
// https://stackoverflow.com/questions/45070642/springboot-doesnt-handle-org-hibernate-exception-constraintviolationexception
@@ -1,32 +0,0 @@
package org.hydev.clock_api.controller;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.hydev.clock_api.error.ErrorCode;
import org.hydev.clock_api.repository.UserRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import java.util.List;
@Aspect
@Component
public class RegistryControllerAspect {
private final UserRepository userRepository;
public RegistryControllerAspect(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Around(value = "execution(* RegistryController.register(String, String)) " +
"&& args(username, password)", argNames = "pjp, username, password")
// Even if I'm not use the password argument, I still should write it out!
private Object checkUsernameExists(ProceedingJoinPoint pjp, String username, String password) throws Throwable {
if (userRepository.existsByUsername(username))
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE)
.body(List.of(ErrorCode.USER_NAME_ALREADY_EXISTS));
return pjp.proceed();
}
}
@@ -15,15 +15,16 @@ import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.List;
@Validated
@RestController
@RequestMapping("/user")
public class RegistryController {
public class UserController {
private final UserRepository userRepository;
@Autowired
public RegistryController(UserRepository userRepository) {
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@@ -41,7 +42,9 @@ public class RegistryController {
@RequestHeader String password
) {
// First, spring will check args. If not pass there regex, raise ConstraintViolationException.
// Then, the aspect will check username if already exists.
// Check if username not exists.
if (userRepository.existsByUsername(username))
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(ErrorCode.USER_NAME_ALREADY_EXISTS);
User user = new User();
user.setUsername(username);