Meenapintu/Restweb

global error handler for http_listener

art-in opened this issue · 3 comments

hi, there's handler::handle_error, but i don't see where it's used.

is there way to set global error handler, so i dont need to try/catch all handlers to log exceptions? otherwise looks like http_listener just swallows exception and replies with 500.

HI @artin-phares handler::handle_error designed to use as a global error handler but it's not used right now.

Anyway Global error handler can be used like

 void handler::handle_get(http_request message) {
    ucout <<  message.to_string() << endl;
    auto paths = http::uri::split_path(http::uri::decode(message.relative_uri().path()));

    message.relative_uri().path();
	//Dbms* d  = new Dbms();
    //d->connect();

      concurrency::streams::fstream::open_istream(U("static/index.html"), std::ios::in).then([=](concurrency::streams::istream is)
    {
        message.reply(status_codes::OK, is,  U("text/html"))
		.then([](pplx::task<void> t)
		{
			error_handle(t);
	});
    }).then([](pplx::task<void>t)
	{
		 error_handle(t);
	});

    return;

Thanks @artin-phares , I'll update it.

well, that doesn't look good to me..

the idea is to keep error handler away from request handlers as much as possible.

i'm currently using handle wrapper and lambdas like this:

void handle(web::http::http_request req, std::function<void()> handler) {
  try {
    handler();
  } catch (std::exception &e) {
    ucerr << "Failed to handle request: " << e.what() << std::endl;
    ucerr << req.to_string() << std::endl;
    throw e;
  }
}

void handler::handle_post(web::http::http_request req) {
  handle(req, [&] {
    // ... do stuff ...
    req.reply(web::http::status_codes::OK);
  });
};

void handler::handle_get(web::http::http_request req) {
  handle(req, [&] {
    // ... do stuff ...
    req.reply(web::http::status_codes::OK, resp);
  });
};

which doesn't look good either.

what i really want to do is something like this:

m_listener.set_error_handler(&handle_error);

handle_error(web::http::http_request req, std::exception e) {
  // handle exception thrown from any registered handler of this listener.
  // reply with custom status code/text, log, etc.
}

m_listener.set_error_handler(&handle_error); is a good idea. I"m not aware that there is a such functionality or not as i'm not working on it frequently .

I think you have to deep dive and figure out.