Skip to content

Commit 2c49d51

Browse files
committed
chore: error response on unhandled route
1 parent 4183c87 commit 2c49d51

File tree

2 files changed

+23
-19
lines changed

2 files changed

+23
-19
lines changed

example/server/main.cpp

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -67,23 +67,8 @@ int server_main( int argc, char* argv[] )
6767
(unsigned short)std::atoi(argv[2]),
6868
std::atoi(argv[4]));
6969

70-
srv.wwwroot.use("/log", serve_log_admin(app));
71-
srv.wwwroot.use("/", serve_static( argv[3] ));
72-
73-
// unhandled errors
74-
srv.wwwroot.err(
75-
[]( Request&, Response& res,
76-
system::error_code const& ec)
77-
{
78-
http_proto::status sc;
79-
if(ec == system::errc::no_such_file_or_directory)
80-
sc = http_proto::status::not_found;
81-
else
82-
sc = http_proto::status::internal_server_error;
83-
res.status(sc);
84-
res.set_body(ec.message());
85-
return error::success;
86-
});
70+
//srv.wwwroot.use("/log", serve_log_admin(app));
71+
//srv.wwwroot.use("/", serve_static( argv[3] ));
8772

8873
app.start();
8974
srv.attach();

include/boost/beast2/server/http_session.hpp

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#include <boost/beast2/detail/config.hpp>
1414
#include <boost/beast2/application.hpp>
1515
#include <boost/beast2/log_service.hpp>
16+
#include <boost/beast2/format.hpp>
1617
#include <boost/beast2/read.hpp>
1718
#include <boost/beast2/write.hpp>
1819
#include <boost/beast2/server/any_lambda.hpp>
@@ -217,16 +218,34 @@ on_read(
217218
route_state_ = {};
218219
ec = rr_(*preq_, *pres_, route_state_);
219220

221+
if(! ec.failed())
222+
goto do_write;
223+
220224
if(ec == error::detach)
221225
{
222226
// make sure they called detach()
223227
BOOST_ASSERT(pwg_);
224228
return;
225229
}
226230

227-
if(ec.failed())
231+
if(ec == error::next)
228232
{
229-
// give a default error response?
233+
// unhandled
234+
pres_->status(http_proto::status::not_found);
235+
std::string s;
236+
format_to(s, "The requested URL {} was not found on this server.", preq_->target);
237+
pres_->set_body(s);
238+
pres_->m.set_keep_alive(false);
239+
goto do_write;
240+
}
241+
242+
// error message of last resort
243+
{
244+
pres_->status(http_proto::status::internal_server_error);
245+
std::string s;
246+
format_to(s, "An internal server error occurred: {}", ec.message());
247+
pres_->set_body(s);
248+
pres_->m.set_keep_alive(false);
230249
}
231250

232251
do_write:

0 commit comments

Comments
 (0)