|
30 | 30 | import org.slf4j.Logger;
|
31 | 31 | import org.slf4j.LoggerFactory;
|
32 | 32 |
|
| 33 | +import io.netty.handler.codec.http.HttpHeaderNames; |
| 34 | +import io.netty.handler.codec.http.HttpResponseStatus; |
33 | 35 | import io.opentracing.Span;
|
34 | 36 | import io.vertx.core.buffer.Buffer;
|
35 | 37 | import io.vertx.core.http.HttpHeaders;
|
| 38 | +import io.vertx.core.http.HttpMethod; |
36 | 39 | import io.vertx.core.http.HttpServerRequest;
|
37 | 40 | import io.vertx.core.http.HttpServerResponse;
|
38 | 41 | import io.vertx.core.json.JsonArray;
|
39 | 42 | import io.vertx.core.json.JsonObject;
|
| 43 | +import io.vertx.ext.web.Router; |
40 | 44 | import io.vertx.ext.web.RoutingContext;
|
41 | 45 |
|
42 | 46 | /**
|
@@ -371,4 +375,27 @@ public static void logErrorIfInvalidURI(final HttpServerRequest req, final Span
|
371 | 375 | TracingHelper.logError(span, "invalid request URI", e);
|
372 | 376 | }
|
373 | 377 | }
|
| 378 | + |
| 379 | + /** |
| 380 | + * Adds an error handler for {@code 404} status requests to the given router. |
| 381 | + * The handler adds an error log entry in the request span and sets a response body (if it's not a HEAD request). |
| 382 | + * |
| 383 | + * @param router The router to add the error handler to. |
| 384 | + * @throws NullPointerException if router is {@code null}. |
| 385 | + */ |
| 386 | + public static void addDefault404ErrorHandler(final Router router) { |
| 387 | + Objects.requireNonNull(router); |
| 388 | + router.errorHandler(404, ctx -> { |
| 389 | + ctx.response().setStatusCode(404); |
| 390 | + Optional.ofNullable(HttpServerSpanHelper.serverSpan(ctx)) |
| 391 | + .ifPresent(span -> TracingHelper.logError(span, HttpResponseStatus.valueOf(404).reasonPhrase())); |
| 392 | + if (ctx.request().method() != HttpMethod.HEAD) { |
| 393 | + ctx.response() |
| 394 | + .putHeader(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8") |
| 395 | + .end("<html><body><h1>Resource not found</h1></body></html>"); |
| 396 | + } else { |
| 397 | + ctx.response().end(); |
| 398 | + } |
| 399 | + }); |
| 400 | + } |
374 | 401 | }
|
0 commit comments