Skip to content

Commit 4c6ab0f

Browse files
committed
feat: improve error handling and status code mapping in HttpServer
- Add explicit catch block for ApplicationException to handle domain-specific errors. - Implement mapping from ApplicationException status codes to ResponseStatus. - Default to INTERNAL_SERVER_ERROR (500) if an invalid status code is provided. - Ensure error messages are written to the response using StandardCharsets.UTF_8. - Updated logging to provide more descriptive error messages.
1 parent 1f51605 commit 4c6ab0f

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/main/java/org/tinystruct/system/HttpServer.java

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import java.io.*;
3232
import java.net.InetSocketAddress;
3333
import java.nio.charset.Charset;
34+
import java.nio.charset.StandardCharsets;
3435
import java.util.Objects;
3536
import java.util.concurrent.Executors;
3637
import java.util.logging.Level;
@@ -304,8 +305,19 @@ public void handle(HttpExchange exchange) throws IOException {
304305

305306
// Process the request using TinyStruct's DefaultHandler logic
306307
processRequest(request, response, context);
308+
} catch (ApplicationException e) {
309+
logger.log(Level.SEVERE, e.getMessage(), e);
310+
int status = e.getStatus();
311+
ResponseStatus responseStatus = ResponseStatus.valueOf(status);
312+
if (responseStatus == null)
313+
responseStatus = ResponseStatus.INTERNAL_SERVER_ERROR;
314+
315+
try {
316+
sendErrorResponse(exchange, responseStatus.code(), e.getMessage());
317+
} catch (Exception ignored) {
318+
}
307319
} catch (Exception e) {
308-
logger.log(Level.SEVERE, "Error processing request", e);
320+
logger.log(Level.SEVERE, e.getMessage(), e);
309321
// Try to send error only if headers haven't been committed yet
310322
try {
311323
sendErrorResponse(exchange, 500, "Internal Server Error: " + e.getMessage());
@@ -561,8 +573,12 @@ private void processRequest(ServerRequest request, ServerResponse response, Cont
561573
logger.log(Level.SEVERE, "Error in request processing", e);
562574
response.setContentType("text/plain; charset=UTF-8");
563575
int status = e.getStatus();
564-
response.setStatus(org.tinystruct.http.ResponseStatus.valueOf(status));
565-
response.writeAndFlush("500 - Internal Server Error".getBytes("UTF-8"));
576+
ResponseStatus responseStatus = ResponseStatus.valueOf(status);
577+
if (responseStatus == null)
578+
responseStatus = ResponseStatus.INTERNAL_SERVER_ERROR;
579+
580+
response.setStatus(responseStatus);
581+
response.writeAndFlush(e.getMessage().getBytes(StandardCharsets.UTF_8));
566582
response.close();
567583
}
568584
}
@@ -642,4 +658,3 @@ private void sendErrorResponse(HttpExchange exchange, int statusCode, String mes
642658

643659
}
644660
}
645-

0 commit comments

Comments
 (0)