exception.cpp 1.21 KB
#include "socket-cpp/exception.h"
#include "socket-cpp/platform.h"
#include <cstring>

// Used to explicitly ignore the returned value of a function call.
#define ignore_result(x) if (x) {}

using namespace std;
using namespace osdev::components::socket-cpp;

sys_error::sys_error(int err) : runtime_error(error_str(err)), errno_(err)
{
}

std::string sys_error::error_str(int err)
{
	char buf[1024];
	buf[0] = '\x0';

	#if defined(_WIN32)
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			buf, sizeof(buf), NULL);
    #else
    	#ifdef _GNU_SOURCE
			#if !defined(__GLIBC__)
			// use the XSI standard behavior.
				int e = strerror_r(err, buf, sizeof(buf));
				auto s = strerror(e);
				return s ? std::string(s) : std::string();
			#else
			// assume GNU exception
				auto s = strerror_r(err, buf, sizeof(buf));
				return s ? std::string(s) : std::string();
			#endif
        #else
            ignore_result(strerror_r(err, buf, sizeof(buf)));
        #endif
    #endif
	return std::string(buf);
}

getaddrinfo_error::getaddrinfo_error(int err, const string& hostname)
    : runtime_error(gai_strerror(err)), error_(err), hostname_(hostname)
{
}