better error handling in HTTP server
This commit is contained in:
parent
198b04c2e3
commit
8992065a10
1 changed files with 51 additions and 30 deletions
|
@ -47,10 +47,13 @@ namespace SAPIServer
|
||||||
{
|
{
|
||||||
var context = listener.GetContext();
|
var context = listener.GetContext();
|
||||||
ThreadPool.QueueUserWorkItem(_ =>
|
ThreadPool.QueueUserWorkItem(_ =>
|
||||||
|
{
|
||||||
|
var uri = context.Request.RawUrl.Split('?')[0];
|
||||||
|
var ip = context.Request.RemoteEndPoint.Address;
|
||||||
|
try
|
||||||
{
|
{
|
||||||
Dictionary<string, Func<HttpListenerContext, byte[]>> handlerDict;
|
Dictionary<string, Func<HttpListenerContext, byte[]>> handlerDict;
|
||||||
// TODO: Make query params parsable
|
// TODO: Make query params parsable
|
||||||
var uri = context.Request.RawUrl.Split('?')[0];
|
|
||||||
byte[] response;
|
byte[] response;
|
||||||
switch (context.Request.HttpMethod)
|
switch (context.Request.HttpMethod)
|
||||||
{
|
{
|
||||||
|
@ -81,11 +84,29 @@ namespace SAPIServer
|
||||||
context.Response.StatusCode = 404;
|
context.Response.StatusCode = 404;
|
||||||
context.Response.ContentType = "text/plain";
|
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.ContentLength64 = response.Length;
|
||||||
context.Response.OutputStream.Write(response, 0, response.Length);
|
context.Response.OutputStream.Write(response, 0, response.Length);
|
||||||
context.Response.OutputStream.Close();
|
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}");
|
||||||
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue