How to pass http exception to calling (main) program?

Feb 20, 2014 at 1:26 AM
When an http exception occurs, the catch within the error_handler() displays a message. What is the best practice/code for passing the error message from pplx::task error_handler() back to main()? If an error occurs, I want to bypass any further http listening code, log and exit.

Below is a minimal http listener to demonstrate the question:
// CanonicalCppRestSdkServer.cpp : Minimal web server. Performs HTTP GET only. Listens on port 3901.

#include "stdafx.h"
#include "cpprest\http_listener.h"

void handle_error(pplx::task<void>& t)
{
    try
    {
        t.get();
    }
    catch (const web::http::http_exception &e)
    {
        std::wcout << "http exception:" << e.what();
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    web::http::uri uri(L"http://127.0.0.1:3901");
    std::wcout << uri.to_string();
    web::http::experimental::listener::http_listener listener(uri);
    listener.support(web::http::methods::GET, [](web::http::http_request message){
        message.reply(web::http::status_codes::OK, L"hello world").then(std::bind(&handle_error, std::placeholders::_1));
    });
    listener.open().then(std::bind(&handle_error, std::placeholders::_1)).wait();

    std::wcout << utility::string_t(L"Listening for requests at: ") << listener.uri().to_string() << std::endl;
    std::wcout << L"Hit Enter to close the listener.";
    std::string line;
    std::getline(std::cin, line);

    listener.close().wait();

    return 0;
}
Feb 20, 2014 at 2:46 AM
Hi BSalita,

If you want to know in your main function when an error occurs sending a response you are going to have to use some sort of event to signal an error has occurred. If you weren't blocking on the user's input you could just use an event or a pplx::task backed by a pplx::task_completion_event which would be set in handle_error. With what you have now you are going to need to find a way to unblock you thread waiting on the std::getline(...) to be satisfied.

Also as a side note do you really want your listener to close and stop if an error occurs sending a response to one of the requests? In practice you might want to log, but probably not bring down the whole server. Something as simple as the client closing the connection early could cause the server to stop listening.

Steve
Feb 20, 2014 at 6:57 AM
So there needs to be two or more error processings. One state for something like a uri error where the uri is invalid or requires administrator mode. In that case it's impossible to continue to add that listener. Another state, for uninteresting errors such as the client closing the connection, the server is not distressed and must continue being a good listener. I suppose there could be other states such as receiving a remote command to shutdown.