feat: Added problem-details [RFC-7807] for a message mutation error
authorKai Moritz <kai@juplo.de>
Mon, 26 Dec 2022 13:50:51 +0000 (14:50 +0100)
committerKai Moritz <kai@juplo.de>
Sun, 15 Jan 2023 18:32:58 +0000 (19:32 +0100)
src/main/java/de/juplo/kafka/chatroom/api/ChatroomControllerAdvice.java [new file with mode: 0644]
src/main/java/de/juplo/kafka/chatroom/domain/Chatroom.java
src/main/java/de/juplo/kafka/chatroom/domain/MessageMutationException.java [new file with mode: 0644]

diff --git a/src/main/java/de/juplo/kafka/chatroom/api/ChatroomControllerAdvice.java b/src/main/java/de/juplo/kafka/chatroom/api/ChatroomControllerAdvice.java
new file mode 100644 (file)
index 0000000..d98abbb
--- /dev/null
@@ -0,0 +1,26 @@
+package de.juplo.kafka.chatroom.api;
+
+import de.juplo.kafka.chatroom.domain.MessageMutationException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ProblemDetail;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.reactive.result.method.annotation.ResponseEntityExceptionHandler;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+
+@ControllerAdvice
+public class ChatroomControllerAdvice extends ResponseEntityExceptionHandler
+{
+  @ExceptionHandler(MessageMutationException.class)
+  public final Mono<ResponseEntity<Object>> handleException(MessageMutationException e, ServerWebExchange exchange)
+  {
+    final HttpStatus status = HttpStatus.BAD_REQUEST;
+    ProblemDetail body = ProblemDetail.forStatusAndDetail(status, e.getMessage());
+    body.setProperty("new", e.getToAdd());
+    body.setProperty("existing", e.getExisting());
+    return handleExceptionInternal(e, body, null, status, exchange);
+  }
+}
index 1d7ee2a..62d33f2 100644 (file)
@@ -48,7 +48,7 @@ public class Chatroom
     {
       log.info("Message with key {} already exists; {}", key, existing);
       if (!message.equals(existing))
-        throw new IllegalArgumentException("Messages are imutable!");
+        throw new MessageMutationException(message, existing);
       return Mono.empty();
     }
 
diff --git a/src/main/java/de/juplo/kafka/chatroom/domain/MessageMutationException.java b/src/main/java/de/juplo/kafka/chatroom/domain/MessageMutationException.java
new file mode 100644 (file)
index 0000000..ceeea24
--- /dev/null
@@ -0,0 +1,19 @@
+package de.juplo.kafka.chatroom.domain;
+
+import lombok.Getter;
+
+
+public class MessageMutationException extends RuntimeException
+{
+  @Getter
+  private final Message toAdd;
+  @Getter
+  private final Message existing;
+
+  public MessageMutationException(Message toAdd, Message existing)
+  {
+    super("Messages are imutable!");
+    this.toAdd = toAdd;
+    this.existing = existing;
+  }
+}