]> git.tdb.fi Git - libs/net.git/blobdiff - source/http/server.cpp
Improve error handling
[libs/net.git] / source / http / server.cpp
index f0474fd18e993c57de16b1a3f51c07dc260f069f..f985bf994526bf871844b97cfd263f2ee56ee2ef 100644 (file)
@@ -1,6 +1,8 @@
 #include <exception>
+#include <typeinfo>
 #include <msp/core/maputils.h>
 #include <msp/core/refptr.h>
+#include <msp/debug/demangle.h>
 #include <msp/net/inet.h>
 #include <msp/net/resolve.h>
 #include <msp/net/streamsocket.h>
@@ -90,11 +92,19 @@ void Server::client_data_available(Client &cl)
                        break;
                }
 
-       char rbuf[4096];
-       unsigned len = cl.sock->read(rbuf, sizeof(rbuf));
-       if(cl.stale)
+       try
+       {
+               char rbuf[4096];
+               unsigned len = cl.sock->read(rbuf, sizeof(rbuf));
+               if(cl.stale)
+                       return;
+               cl.in_buf.append(rbuf, len);
+       }
+       catch(const exception &)
+       {
+               cl.stale = true;
                return;
-       cl.in_buf.append(rbuf, len);
+       }
 
        RefPtr<Response> response;
        if(!cl.request)
@@ -123,14 +133,15 @@ void Server::client_data_available(Client &cl)
                        catch(const exception &e)
                        {
                                response = new Response(BAD_REQUEST);
-                               response->add_content(e.what());
+                               response->add_content(format("An error occurred while parsing request headers:\ntype: %s\nwhat: %s",
+                                       Debug::demangle(typeid(e).name()), e.what()));
                        }
                        cl.in_buf = string();
                }
        }
        else
        {
-               len = cl.request->parse_content(cl.in_buf);
+               unsigned len = cl.request->parse_content(cl.in_buf);
                cl.in_buf.erase(0, len);
        }
 
@@ -164,7 +175,8 @@ void Server::client_data_available(Client &cl)
                        responses.erase(cl.response);
                        cl.response = 0;
                        response = new Response(INTERNAL_ERROR);
-                       response->add_content(e.what());
+                       response->add_content(format("An error occurred while processing the request:\ntype: %s\nwhat: %s",
+                               Debug::demangle(typeid(e).name()), e.what()));
                }
        }
 
@@ -176,7 +188,17 @@ void Server::send_response(Client &cl, Response &resp)
 {
        if(cl.keepalive)
                resp.set_header("Connection", "keep-alive");
-       cl.sock->write(resp.str());
+
+       try
+       {
+               cl.sock->write(resp.str());
+       }
+       catch(const exception &)
+       {
+               cl.stale = true;
+               return;
+       }
+
        cl.async = false;
        if(cl.keepalive)
        {