Fix error handling in server examples

This commit is contained in:
Evgeniy
2016-09-25 09:14:27 -04:00
committed by Vinnie Falco
parent 0c0b2f2545
commit d5d8e2fcd2
2 changed files with 30 additions and 23 deletions

View File

@@ -249,20 +249,23 @@ private:
asio::placeholders::error)); asio::placeholders::error));
return; return;
} }
resp_type res;
res.status = 200;
res.reason = "OK";
res.version = req_.version;
res.headers.insert("Server", "http_async_server");
res.headers.insert("Content-Type", mime_type(path));
res.body = path;
try try
{ {
resp_type res;
res.status = 200;
res.reason = "OK";
res.version = req_.version;
res.headers.insert("Server", "http_async_server");
res.headers.insert("Content-Type", mime_type(path));
res.body = path;
prepare(res); prepare(res);
async_write(sock_, std::move(res),
std::bind(&peer::on_write, shared_from_this(),
asio::placeholders::error));
} }
catch(std::exception const& e) catch(std::exception const& e)
{ {
res = {}; response_v1<string_body> res;
res.status = 500; res.status = 500;
res.reason = "Internal Error"; res.reason = "Internal Error";
res.version = req_.version; res.version = req_.version;
@@ -271,10 +274,10 @@ private:
res.body = res.body =
std::string{"An internal error occurred"} + e.what(); std::string{"An internal error occurred"} + e.what();
prepare(res); prepare(res);
async_write(sock_, std::move(res),
std::bind(&peer::on_write, shared_from_this(),
asio::placeholders::error));
} }
async_write(sock_, std::move(res),
std::bind(&peer::on_write, shared_from_this(),
asio::placeholders::error));
} }
void on_write(error_code ec) void on_write(error_code ec)

View File

@@ -172,33 +172,37 @@ private:
write(sock, res, ec); write(sock, res, ec);
if(ec) if(ec)
break; break;
return;
} }
resp_type res;
res.status = 200;
res.reason = "OK";
res.version = req.version;
res.headers.insert("Server", "http_sync_server");
res.headers.insert("Content-Type", mime_type(path));
res.body = path;
try try
{ {
resp_type res;
res.status = 200;
res.reason = "OK";
res.version = req.version;
res.headers.insert("Server", "http_sync_server");
res.headers.insert("Content-Type", mime_type(path));
res.body = path;
prepare(res); prepare(res);
write(sock, res, ec);
if(ec)
break;
} }
catch(std::exception const& e) catch(std::exception const& e)
{ {
res = {}; response_v1<string_body> res;
res.status = 500; res.status = 500;
res.reason = "Internal Error"; res.reason = "Internal Error";
res.version = req.version; res.version = req.version;
res.headers.insert("Server", "http_sync_server"); res.headers.insert("Server", "http_sync_server");
res.headers.insert("Content-Type", "text/html"); res.headers.insert("Content-Type", "text/html");
res.body = res.body =
std::string{"An internal error occurred"} + e.what(); std::string{"An internal error occurred: "} + e.what();
prepare(res); prepare(res);
write(sock, res, ec);
if(ec)
break;
} }
write(sock, res, ec);
if(ec)
break;
} }
fail(id, ec); fail(id, ec);
} }