better error handling in HTTP server

This commit is contained in:
Elijah 2024-07-02 20:48:40 -04:00
parent 198b04c2e3
commit 8992065a10

View file

@ -47,10 +47,13 @@ namespace SAPIServer
{
var context = listener.GetContext();
ThreadPool.QueueUserWorkItem(_ =>
{
var uri = context.Request.RawUrl.Split('?')[0];
var ip = context.Request.RemoteEndPoint.Address;
try
{
Dictionary<string, Func<HttpListenerContext, byte[]>> handlerDict;
// TODO: Make query params parsable
var uri = context.Request.RawUrl.Split('?')[0];
byte[] response;
switch (context.Request.HttpMethod)
{
@ -81,11 +84,29 @@ namespace SAPIServer
context.Response.StatusCode = 404;
context.Response.ContentType = "text/plain";
}
else response = handler(context);
else
{
try
{
response = handler(context);
} catch (Exception e)
{
response = Encoding.UTF8.GetBytes("Internal Server Error");
context.Response.StatusCode = 500;
context.Response.ContentType = "text/plain";
Console.Error.WriteLine($"[{DateTime.Now:u}] {ip} - {context.Request.HttpMethod} {context.Request.RawUrl} - Handler Failed: {e.Message}");
}
}
context.Response.ContentLength64 = response.Length;
context.Response.OutputStream.Write(response, 0, response.Length);
context.Response.OutputStream.Close();
Console.WriteLine($"[{DateTime.Now:u}] {context.Request.RemoteEndPoint.Address} - {context.Request.HttpMethod} {context.Request.RawUrl} - {context.Response.StatusCode}");
Console.WriteLine($"[{DateTime.Now:u}] {ip} - {context.Request.HttpMethod} {context.Request.RawUrl} - {context.Response.StatusCode}");
} catch (Exception e)
{
Console.Error.WriteLine($"[{DateTime.Now:u}] {ip} - {context.Request.HttpMethod} {context.Request.RawUrl} - Exception: {e.Message}");
}
});
}
}