1 package de.juplo.kafka.chatroom.api;
3 import de.juplo.kafka.chatroom.domain.MessageMutationException;
4 import org.springframework.beans.factory.annotation.Value;
5 import org.springframework.http.HttpStatus;
6 import org.springframework.http.ProblemDetail;
7 import org.springframework.web.bind.annotation.ControllerAdvice;
8 import org.springframework.web.bind.annotation.ExceptionHandler;
9 import org.springframework.web.server.ServerWebExchange;
10 import org.springframework.web.util.UriComponentsBuilder;
12 import java.util.Date;
16 public class ChatroomControllerAdvice
18 @Value("${server.context-path:/}")
21 @ExceptionHandler(MessageMutationException.class)
22 public final ProblemDetail handleException(
23 MessageMutationException e,
24 ServerWebExchange exchange,
25 UriComponentsBuilder uriComponentsBuilder)
27 final HttpStatus status = HttpStatus.BAD_REQUEST;
28 ProblemDetail problem = ProblemDetail.forStatus(status);
30 problem.setProperty("timestamp", new Date());
32 problem.setProperty("requestId", exchange.getRequest().getId());
34 problem.setType(uriComponentsBuilder.replacePath(contextPath).path("/problem/message-mutation").build().toUri());
35 StringBuilder stringBuilder = new StringBuilder();
36 stringBuilder.append(status.getReasonPhrase());
37 stringBuilder.append(" - ");
38 stringBuilder.append(e.getMessage());
39 problem.setTitle(stringBuilder.toString());
41 stringBuilder.setLength(0);
42 stringBuilder.append("The existing message with user=");
43 stringBuilder.append(e.getExisting().getUser());
44 stringBuilder.append(" and id=");
45 stringBuilder.append(e.getExisting().getId());
46 stringBuilder.append(" cannot be mutated!");
47 problem.setDetail(stringBuilder.toString());
49 problem.setProperty("mutatedMessage", e.getMutated());
51 problem.setProperty("existingMessage", e.getExisting());