update error handling code
This commit is contained in:
parent
5e0d5b6db2
commit
419699bc0d
@ -21,10 +21,10 @@
|
|||||||
#include <fcntl.h>
|
#include <fcntl.h>
|
||||||
|
|
||||||
using SOCKET = int;
|
using SOCKET = int;
|
||||||
|
#endif // _WIN32
|
||||||
#endif
|
|
||||||
|
|
||||||
#include "debug/Logger.hpp"
|
#include "debug/Logger.hpp"
|
||||||
|
#include "util/stringutil.hpp"
|
||||||
|
|
||||||
using namespace network;
|
using namespace network;
|
||||||
|
|
||||||
@ -191,6 +191,31 @@ public:
|
|||||||
static inline int closesocket(int descriptor) noexcept {
|
static inline int closesocket(int descriptor) noexcept {
|
||||||
return close(descriptor);
|
return close(descriptor);
|
||||||
}
|
}
|
||||||
|
static inline void handle_socket_error(const std::string& message) {
|
||||||
|
int err = errno;
|
||||||
|
throw std::runtime_error(
|
||||||
|
message+" [errno=" + std::to_string(err) +
|
||||||
|
"]: " + std::string(strerror(err))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
static inline void handle_socket_error() {
|
||||||
|
wchar_t* s = nullptr;
|
||||||
|
FormatMessageW(
|
||||||
|
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
|
||||||
|
FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||||
|
nullptr,
|
||||||
|
WSAGetLastError(),
|
||||||
|
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||||
|
(LPWSTR)&s,
|
||||||
|
0,
|
||||||
|
nullptr
|
||||||
|
);
|
||||||
|
assert(s != nullptr);
|
||||||
|
std::string errorString = util::wstr2str_utf8(std::wstring(s));
|
||||||
|
LocalFree(s);
|
||||||
|
throw std::runtime_error(message+"; "+errorString)
|
||||||
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
static inline int connectsocket(
|
static inline int connectsocket(
|
||||||
@ -328,16 +353,12 @@ public:
|
|||||||
throw std::runtime_error("Failed to make socket non-blocking");
|
throw std::runtime_error("Failed to make socket non-blocking");
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
int res = connectsocket(descriptor, addrinfo->ai_addr, addrinfo->ai_addrlen);
|
int res = connectsocket(descriptor, addrinfo->ai_addr, addrinfo->ai_addrlen);
|
||||||
if (res == -1) {
|
if (res == -1) {
|
||||||
closesocket(descriptor);
|
closesocket(descriptor);
|
||||||
freeaddrinfo(addrinfo);
|
freeaddrinfo(addrinfo);
|
||||||
|
handle_socket_error("Connect failed");
|
||||||
int err = errno;
|
|
||||||
throw std::runtime_error(
|
|
||||||
"Connect failed [errno=" + std::to_string(err) +
|
|
||||||
"]: " + std::string(strerror(err))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
logger.info() << "connected to " << address << " ["
|
logger.info() << "connected to " << address << " ["
|
||||||
<< to_string(addrinfo) << ":" << port << "]";
|
<< to_string(addrinfo) << ":" << port << "]";
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user