def raise_on_error(f):
    """
    This decorator throws a WinError whenever GetLastError() returns an error.
    As as special case, ERROR_IO_PENDING is ignored.
    """

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        result = f(*args, **kwargs)
        retcode = GetLastError()
        if retcode and retcode != ERROR_IO_PENDING:
            err = WinError(code=retcode)
            windll.kernel32.SetLastError(0)  # clear error code so that we don't raise twice.
            raise err
        return result

    return wrapper