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,6 +249,8 @@ private:
asio::placeholders::error)); asio::placeholders::error));
return; return;
} }
try
{
resp_type res; resp_type res;
res.status = 200; res.status = 200;
res.reason = "OK"; res.reason = "OK";
@@ -256,13 +258,14 @@ private:
res.headers.insert("Server", "http_async_server"); res.headers.insert("Server", "http_async_server");
res.headers.insert("Content-Type", mime_type(path)); res.headers.insert("Content-Type", mime_type(path));
res.body = path; res.body = path;
try
{
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,11 +274,11 @@ 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), async_write(sock_, std::move(res),
std::bind(&peer::on_write, shared_from_this(), std::bind(&peer::on_write, shared_from_this(),
asio::placeholders::error)); asio::placeholders::error));
} }
}
void on_write(error_code ec) void on_write(error_code ec)
{ {

View File

@@ -172,7 +172,10 @@ private:
write(sock, res, ec); write(sock, res, ec);
if(ec) if(ec)
break; break;
return;
} }
try
{
resp_type res; resp_type res;
res.status = 200; res.status = 200;
res.reason = "OK"; res.reason = "OK";
@@ -180,26 +183,27 @@ private:
res.headers.insert("Server", "http_sync_server"); res.headers.insert("Server", "http_sync_server");
res.headers.insert("Content-Type", mime_type(path)); res.headers.insert("Content-Type", mime_type(path));
res.body = path; res.body = path;
try
{
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); write(sock, res, ec);
if(ec) if(ec)
break; break;
} }
}
fail(id, ec); fail(id, ec);
} }
}; };