Skip to content

Commit aa425dc

Browse files
committed
Add default error handler for HTTP requests with status 404.
Signed-off-by: Carsten Lohmann <[email protected]>
1 parent d0da950 commit aa425dc

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

adapters/http-base/src/main/java/org/eclipse/hono/adapter/http/AbstractVertxBasedHttpProtocolAdapter.java

+1
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,7 @@ protected Router createRouter() {
298298
}
299299
ctx.next();
300300
});
301+
HttpUtils.addDefault404ErrorHandler(router);
301302
return router;
302303
}
303304

service-base/src/main/java/org/eclipse/hono/service/http/HttpServiceBase.java

+1
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@ protected Router createRouter() {
207207
ctx.next();
208208
});
209209
addAuthHandler(router);
210+
HttpUtils.addDefault404ErrorHandler(router);
210211
return router;
211212
}
212213

service-base/src/main/java/org/eclipse/hono/service/http/HttpUtils.java

+27
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,17 @@
3030
import org.slf4j.Logger;
3131
import org.slf4j.LoggerFactory;
3232

33+
import io.netty.handler.codec.http.HttpHeaderNames;
34+
import io.netty.handler.codec.http.HttpResponseStatus;
3335
import io.opentracing.Span;
3436
import io.vertx.core.buffer.Buffer;
3537
import io.vertx.core.http.HttpHeaders;
38+
import io.vertx.core.http.HttpMethod;
3639
import io.vertx.core.http.HttpServerRequest;
3740
import io.vertx.core.http.HttpServerResponse;
3841
import io.vertx.core.json.JsonArray;
3942
import io.vertx.core.json.JsonObject;
43+
import io.vertx.ext.web.Router;
4044
import io.vertx.ext.web.RoutingContext;
4145

4246
/**
@@ -371,4 +375,27 @@ public static void logErrorIfInvalidURI(final HttpServerRequest req, final Span
371375
TracingHelper.logError(span, "invalid request URI", e);
372376
}
373377
}
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+
}
374401
}

0 commit comments

Comments
 (0)