maze-server/src/main/java/ch/fritteli/labyrinth/server/handler/AbstractHttpHandler.java

39 lines
1.4 KiB
Java

package ch.fritteli.labyrinth.server.handler;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.StatusCodes;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
@Slf4j
public abstract class AbstractHttpHandler implements HttpHandler {
@Override
public final void handleRequest(@NonNull final HttpServerExchange exchange) {
final Instant start = Instant.now();
try (final MDC.MDCCloseable closeable = MDC.putCloseable("correlationId", UUID.randomUUID().toString())) {
if (exchange.isInIoThread()) {
log.debug("Dispatching request");
exchange.dispatch(this);
return;
}
try {
this.handle(exchange);
} catch (@NonNull final Exception e) {
log.error("Error handling request", e);
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR)
.getResponseSender()
.send(StatusCodes.INTERNAL_SERVER_ERROR_STRING);
}
log.debug("Completed request in {}ms.", start.until(Instant.now(), ChronoUnit.MILLIS));
}
}
protected abstract void handle(@NonNull final HttpServerExchange exchange) throws Exception;
}