Skip to content

Commit 2b3096b

Browse files
committed
Update SocketHandler to return a BadRequest instead of NotFound when there's a parse error
1 parent 7087656 commit 2b3096b

File tree

5 files changed

+27
-4
lines changed

5 files changed

+27
-4
lines changed

src/main/java/httpserver/ResponseWriter.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public ResponseWriter(OutputStream outputStream) {
1919
statuses.put(204, "No Content");
2020
statuses.put(206, "Partial Content");
2121
statuses.put(302, "Found");
22+
statuses.put(400, "Bad Request");
2223
statuses.put(401, "Unauthorized");
2324
statuses.put(404, "Not Found");
2425
statuses.put(405, "Method Not Allowed");

src/main/java/httpserver/SocketHandler.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package httpserver;
22

33
import httpserver.responder.GeneralResponder;
4-
import httpserver.response.NotFoundResponse;
4+
import httpserver.response.BadRequestResponse;
55
import httpserver.response.Response;
66

77
import java.io.IOException;
@@ -33,7 +33,7 @@ public void run() {
3333
Request request = requestParser.parse(inputStream);
3434
response = generalResponder.respond(appConfig, request);
3535
} catch (Exception e) {
36-
response = new NotFoundResponse();
36+
response = new BadRequestResponse();
3737
}
3838

3939
responseWriter.write(response);
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package httpserver.response;
2+
3+
public class BadRequestResponse extends Response {
4+
@Override
5+
public int getStatusCode() {
6+
return 400;
7+
}
8+
}

src/test/java/httpserver/SocketHandlerTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,10 @@ public void callsInjectedPartsCorrectly() throws Exception {
5858
}
5959

6060
@Test
61-
public void returns404ForMalformedRequestLine() throws Exception {
61+
public void returns400ForMalformedRequestLine() throws Exception {
6262
byte[] request = ("".getBytes());
6363

64-
String expected = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
64+
String expected = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n";
6565
assertEquals(expected, stringOutputForRequestBytes(request));
6666
}
6767

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package httpserver.response;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.*;
6+
7+
public class BadRequestResponseTest {
8+
@Test
9+
public void has400StatusCode() throws Exception {
10+
BadRequestResponse badRequestResponse = new BadRequestResponse();
11+
12+
assertEquals(400, badRequestResponse.getStatusCode());
13+
}
14+
}

0 commit comments

Comments
 (0)