Skip to content

Commit d36982a

Browse files
committed
fix: Use responseLength=-1 for empty-body status responses
sendResponseHeaders(code, 0) triggers chunked transfer encoding for empty bodies; -1 is correct for status-only responses with no body. Affects notFoundHandler and the NotFound/MethodNotAllowed/default branches of defaultExceptionHandler.
1 parent 56dd700 commit d36982a

2 files changed

Lines changed: 6 additions & 6 deletions

File tree

src/main/java/com/retailsvc/http/Handlers.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,15 @@ public static ExceptionHandler defaultExceptionHandler() {
3232
exchange.sendResponseHeaders(HTTP_BAD_REQUEST, body.length);
3333
exchange.getResponseBody().write(body);
3434
}
35-
case NotFoundException _ -> exchange.sendResponseHeaders(HTTP_NOT_FOUND, 0);
35+
case NotFoundException _ -> exchange.sendResponseHeaders(HTTP_NOT_FOUND, -1);
3636
case MethodNotAllowedException mna -> {
3737
String allow = mna.allowed().stream().map(Enum::name).collect(Collectors.joining(", "));
3838
exchange.getResponseHeaders().add("Allow", allow);
39-
exchange.sendResponseHeaders(HTTP_BAD_METHOD, 0);
39+
exchange.sendResponseHeaders(HTTP_BAD_METHOD, -1);
4040
}
4141
default -> {
4242
LOG.error("Unhandled exception in handler", t);
43-
exchange.sendResponseHeaders(HTTP_INTERNAL_ERROR, 0);
43+
exchange.sendResponseHeaders(HTTP_INTERNAL_ERROR, -1);
4444
}
4545
}
4646
} catch (IOException io) {
@@ -52,7 +52,7 @@ public static ExceptionHandler defaultExceptionHandler() {
5252
public static HttpHandler notFoundHandler() {
5353
return exchange -> {
5454
try (exchange) {
55-
exchange.sendResponseHeaders(HTTP_NOT_FOUND, 0);
55+
exchange.sendResponseHeaders(HTTP_NOT_FOUND, -1);
5656
}
5757
};
5858
}

src/test/java/com/retailsvc/http/HandlersDefaultExceptionTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,15 @@ void validationExceptionRendersProblem() throws Exception {
4040
void notFoundReturns404() throws Exception {
4141
HttpExchange ex = newExchange(new ByteArrayOutputStream());
4242
Handlers.defaultExceptionHandler().handle(ex, new NotFoundException("GET /x"));
43-
Mockito.verify(ex).sendResponseHeaders(404, 0);
43+
Mockito.verify(ex).sendResponseHeaders(404, -1);
4444
}
4545

4646
@Test
4747
void methodNotAllowedReturns405WithAllowHeader() throws Exception {
4848
HttpExchange ex = newExchange(new ByteArrayOutputStream());
4949
Handlers.defaultExceptionHandler()
5050
.handle(ex, new MethodNotAllowedException(Set.of(HttpMethod.GET, HttpMethod.POST)));
51-
Mockito.verify(ex).sendResponseHeaders(405, 0);
51+
Mockito.verify(ex).sendResponseHeaders(405, -1);
5252
assertThat(ex.getResponseHeaders().getFirst("Allow")).contains("GET").contains("POST");
5353
}
5454
}

0 commit comments

Comments
 (0)