Swiss Frank
Swiss Frank

Reputation: 2422

do you need to clear WSAGetLastError() and if so how?

In Unix, some function calls don't promise to clear errno so you can't detect an error by checking errno unless you clear it yourself before calling. E.g.:

errno = 0;
some_function();
if ( errno ) {
      :
      :

On Windows WSAGetLastError() is used in lieu of errno. Do all WSA functions clear the last error upon success? Or if not, is there a way to clear it manually? If not that either, what do you do?

Upvotes: 0

Views: 627

Answers (2)

David Heffernan
David Heffernan

Reputation: 613053

It depends on the function. If you find a function whose documentation tells you to call WSASetLastError(0) before calling the function, then do so.

However, that would be pretty rare. As with the Win32 error code (managed by GetLastError and SetLastError), the usual pattern is that you should only call WSAGetLastError if the function indicates that it failed. Typically failure is indicated by the return value of the function, but this varies from function to function, and the documentation should be called. The usual pattern is like so:

if (!some_function())
{
    int err = WSAGetLastError();
    // do something with err
}

Generally the function will only promise to call WSASetLastError() in case of failure. So the class mistake that people make is to use WSAGetLastError() to check for errors. That code would be like this:

// don't use this code, it is an anti-pattern
some_function();
int err = WSAGetLastError();
if (err != 0)
    // do something with err
}

You must always carefully read the documentation for each function that you call because there are quite a few different patterns in use.

Upvotes: 2

Anders
Anders

Reputation: 101666

No you don't need to clear it. You only call WSAGetLastError if the function failed.

The normal pattern is just:

if (0 != WSAEventSelect(...))
{
  int error = WSAGetLastError();
  handle_error(error);
}
else
{
  WaitForSingleObject(...);
  ...
}

There is a WSASetLastError function you could call but you normally have no reason to.

Most functions on Windows are implemented so that they only set the error code on failure.

int WSAWhatever()
{
  BOOL success = something() && somethingelse();
  if (!success)
  {
    WSASetLastError(WSASOMETHING);
    return SOCKET_ERROR;
  }
  return 0;
}

There are a couple of places in Win32 where you need to clear the error with SetLastError (GetFileSize etc.) but it is called out in the documentation on MSDN if required.

Upvotes: 2

Related Questions