1 package de.juplo.kafka.chat.backend.api;
3 import de.juplo.kafka.chat.backend.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 ChatBackendControllerAdvice
18 @Value("${server.context-path:/}")
21 @ExceptionHandler(UnknownChatroomException.class)
22 public final ProblemDetail handleException(
23 UnknownChatroomException e,
24 ServerWebExchange exchange,
25 UriComponentsBuilder uriComponentsBuilder)
27 final HttpStatus status = HttpStatus.NOT_FOUND;
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/unknown-chatroom").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("Chatroom unknown: ");
43 stringBuilder.append(e.getChatroomId());
44 problem.setDetail(stringBuilder.toString());
46 problem.setProperty("chatroomId", e.getChatroomId());
51 @ExceptionHandler(MessageMutationException.class)
52 public final ProblemDetail handleException(
53 MessageMutationException e,
54 ServerWebExchange exchange,
55 UriComponentsBuilder uriComponentsBuilder)
57 final HttpStatus status = HttpStatus.BAD_REQUEST;
58 ProblemDetail problem = ProblemDetail.forStatus(status);
60 problem.setProperty("timestamp", new Date());
62 problem.setProperty("requestId", exchange.getRequest().getId());
64 problem.setType(uriComponentsBuilder.replacePath(contextPath).path("/problem/message-mutation").build().toUri());
65 StringBuilder stringBuilder = new StringBuilder();
66 stringBuilder.append(status.getReasonPhrase());
67 stringBuilder.append(" - ");
68 stringBuilder.append(e.getMessage());
69 problem.setTitle(stringBuilder.toString());
71 stringBuilder.setLength(0);
72 stringBuilder.append("The existing message with user=");
73 stringBuilder.append(e.getExisting().getUsername());
74 stringBuilder.append(" and id=");
75 stringBuilder.append(e.getExisting().getId());
76 stringBuilder.append(" cannot be mutated!");
77 problem.setDetail(stringBuilder.toString());
79 problem.setProperty("mutatedMessage", e.getMutated());
81 problem.setProperty("existingMessage", e.getExisting());