1 package de.juplo.kafka.chat.backend.api;
3 import de.juplo.kafka.chat.backend.domain.MessageMutationException;
4 import de.juplo.kafka.chat.backend.domain.UnknownChatroomException;
5 import org.springframework.beans.factory.annotation.Value;
6 import org.springframework.http.HttpStatus;
7 import org.springframework.http.ProblemDetail;
8 import org.springframework.web.bind.annotation.ControllerAdvice;
9 import org.springframework.web.bind.annotation.ExceptionHandler;
10 import org.springframework.web.server.ServerWebExchange;
11 import org.springframework.web.util.UriComponentsBuilder;
13 import java.util.Date;
17 public class ChatBackendControllerAdvice
19 @Value("${server.context-path:/}")
22 @ExceptionHandler(UnknownChatroomException.class)
23 public final ProblemDetail handleException(
24 UnknownChatroomException e,
25 ServerWebExchange exchange,
26 UriComponentsBuilder uriComponentsBuilder)
28 final HttpStatus status = HttpStatus.NOT_FOUND;
29 ProblemDetail problem = ProblemDetail.forStatus(status);
31 problem.setProperty("timestamp", new Date());
33 problem.setProperty("requestId", exchange.getRequest().getId());
35 problem.setType(uriComponentsBuilder.replacePath(contextPath).path("/problem/unknown-chatroom").build().toUri());
36 StringBuilder stringBuilder = new StringBuilder();
37 stringBuilder.append(status.getReasonPhrase());
38 stringBuilder.append(" - ");
39 stringBuilder.append(e.getMessage());
40 problem.setTitle(stringBuilder.toString());
42 stringBuilder.setLength(0);
43 stringBuilder.append("Chatroom unknown: ");
44 stringBuilder.append(e.getChatroomId());
45 problem.setDetail(stringBuilder.toString());
47 problem.setProperty("chatroomId", e.getChatroomId());
52 @ExceptionHandler(MessageMutationException.class)
53 public final ProblemDetail handleException(
54 MessageMutationException e,
55 ServerWebExchange exchange,
56 UriComponentsBuilder uriComponentsBuilder)
58 final HttpStatus status = HttpStatus.BAD_REQUEST;
59 ProblemDetail problem = ProblemDetail.forStatus(status);
61 problem.setProperty("timestamp", new Date());
63 problem.setProperty("requestId", exchange.getRequest().getId());
65 problem.setType(uriComponentsBuilder.replacePath(contextPath).path("/problem/message-mutation").build().toUri());
66 StringBuilder stringBuilder = new StringBuilder();
67 stringBuilder.append(status.getReasonPhrase());
68 stringBuilder.append(" - ");
69 stringBuilder.append(e.getMessage());
70 problem.setTitle(stringBuilder.toString());
72 stringBuilder.setLength(0);
73 stringBuilder.append("The existing message with user=");
74 stringBuilder.append(e.getExisting().getUsername());
75 stringBuilder.append(" and id=");
76 stringBuilder.append(e.getExisting().getId());
77 stringBuilder.append(" cannot be mutated!");
78 problem.setDetail(stringBuilder.toString());
80 problem.setProperty("existingMessage", MessageTo.from(e.getExisting()));
82 problem.setProperty("mutatedText", e.getMutatedText());