Search code examples
dvibed

How to check internet connection status with vibed?


Before app start I need to check if Internet connection is up. What is the best way to do this? I am using vibed.

I wrote next code:

import std.stdio;
import std.string;
import std.conv;
import vibe.d;
import vibe.core.log;
import vibe.http.client;
import vibe.stream.operations;
import vibe.core.driver;

void main()
{

    HTTPClientResponse res = requestHTTP("http://www.example.org/");
    try
    {

        if (res.statusCode != 200)
        {
            logInfo("Check Internet connection, and try again!");
            logInfo("Server response is: " ~ to!string(res.statusCode));
        }
        else
        {
            logInfo("All ok");
        }
    }

    catch (Exception e)
    {
        writeln(e.msg);
    }
}

But if I run it's without Internet connection I got error:

[email protected](1177): No events registered, exiting event loop.

Solution

  • You need to move the line

    HTTPClientResponse res = requestHTTP("http://www.example.org/");
    

    inside the try block to catch the exception.

    If there is no internet connection then there is usually no name service available. This means that there is a high probability that the exception is thrown in case that there is no internet connection.