diff --git a/src/main/java/com/litoralregas/openvpn/common/ApiExceptionHandler.java b/src/main/java/com/litoralregas/openvpn/common/ApiExceptionHandler.java new file mode 100644 index 0000000..b9e7ef5 --- /dev/null +++ b/src/main/java/com/litoralregas/openvpn/common/ApiExceptionHandler.java @@ -0,0 +1,23 @@ +package com.litoralregas.openvpn.common; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestControllerAdvice +public class ApiExceptionHandler { + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(IllegalArgumentException.class) + public Map handleIllegalArgument(IllegalArgumentException exception) { + return Map.of("error", exception.getMessage()); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(MethodArgumentNotValidException.class) + public Map handleValidation(MethodArgumentNotValidException exception) { + return Map.of("error", "Validation failed"); + } +} \ No newline at end of file diff --git a/src/main/java/com/litoralregas/openvpn/router/RouterRepository.java b/src/main/java/com/litoralregas/openvpn/router/RouterRepository.java index 5fc05c5..1598eec 100644 --- a/src/main/java/com/litoralregas/openvpn/router/RouterRepository.java +++ b/src/main/java/com/litoralregas/openvpn/router/RouterRepository.java @@ -1,7 +1,10 @@ package com.litoralregas.openvpn.router; import org.springframework.data.jpa.repository.JpaRepository; + import java.util.UUID; public interface RouterRepository extends JpaRepository { + + boolean existsByLanSubnet(String lanSubnet); } \ No newline at end of file diff --git a/src/main/java/com/litoralregas/openvpn/router/RouterService.java b/src/main/java/com/litoralregas/openvpn/router/RouterService.java index 0730eec..4319969 100644 --- a/src/main/java/com/litoralregas/openvpn/router/RouterService.java +++ b/src/main/java/com/litoralregas/openvpn/router/RouterService.java @@ -20,6 +20,10 @@ public class RouterService { } public Router create(CreateRouterRequest request) { + if (repository.existsByLanSubnet(request.getLanSubnet())) { + throw new IllegalArgumentException("LAN subnet already exists: " + request.getLanSubnet()); + } + LocalDateTime now = LocalDateTime.now(); Router router = new Router();