Date Error Codes Reference

Complete error code definitions and handling guide for date_error.h

Overview

date_error.h defines all error codes, facility codes, and event categories used by the MDTS Date Log library. These codes follow the Windows HRESULT format and provide detailed error information for all date log operations.

Key Features

Error Code Format

All error codes in this library follow the Windows HRESULT format:

// HRESULT format (32-bit value):
//  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
//  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +---+-+-+-----------------------+-------------------------------+
// |Sev|C|R|     Facility          |               Code            |
// +---+-+-+-----------------------+-------------------------------+
//
// Sev (2 bits):  Severity code (0=Success, 1=Info, 2=Warning, 3=Error)
// C (1 bit):     Customer code flag (1 = library-defined error)
// R (1 bit):     Reserved
// Facility (11): Facility code (0x333 = FACILITY_THISLIB)
// Code (16):     Specific error code

HRESULT Structure

Understanding HRESULT Values

Each error code is a 32-bit value that contains specific information about the error. You can extract these components using bitwise operations:

HRESULT Component Extraction

Severity (Bits 30-31):

Determines the type of result

  • 0x0 = Success (S_OK, S_FALSE)
  • 0x1 = Informational
  • 0x2 = Warning
  • 0x3 = Error
Customer Code Flag (Bit 29):

Indicates if the error is defined by the customer/library (1) or system (0)

Facility (Bits 16-26):

Identifies the subsystem that generated the error

  • 0xFFF = FACILITY_APPLICATION
  • 0x333 = FACILITY_THISLIB (Date Log Library)
  • 0x0 = FACILITY_SYSTEM (Windows system)
Status Code (Bits 0-15):

Specific error code within the facility

Checking HRESULT Values

// Recommended macros from winnt.h
#define SUCCEEDED(hr) (((LONG)(hr)) >= 0)
#define FAILED(hr)    (((LONG)(hr)) < 0)

// Extract components
#define HRESULT_SEVERITY(hr) (((hr) >> 30) & 0x3)
#define HRESULT_CUSTOMER(hr) (((hr) >> 29) & 0x1)
#define HRESULT_FACILITY(hr) (((hr) >> 16) & 0x7FF)
#define HRESULT_CODE(hr)     ((hr) & 0xFFFF)

Facility Codes

Facility codes identify the subsystem or component that generated the error. The Date Log library uses multiple facilities for different subsystems:

FACILITY_APPLICATION (0xFFF)

Application-level events and categories

FACILITY_SYSTEM (0x0)

Windows system errors and standard error codes

FACILITY_RUNTIME (0x2)

Runtime environment errors

FACILITY_THISLIB (0x333)

Date Log library-specific errors

FACILITY_IO_ERROR_CODE (0x4)

File I/O and disk operation errors

Event Categories

Event categories are used for categorizing and filtering logged events. The following categories are defined for the Date Log library:

Category Name Value Description
NETWORK_CATEGORY 0x0FFF0001 Network-related events and operations
DATABASE_CATEGORY 0x0FFF0002 Database and SQL operations
INFO_CATEGORY 0x0FFF0003 UI and informational events
IO_CATEGORY 0x0FFF0004 File I/O and disk operations
CONFIG_CATEGORY 0x0FFF0005 Configuration and settings events
ENCRYPTION_CATEGORY 0x0FFF0006 Encryption and security operations
SYSTEM_CATEGORY 0x0FFF0007 System-level events
SECURITY_CATEGORY 0x0FFF0008 Security and access control events

Informational Codes

Informational codes indicate successful operations or non-error conditions that may be logged or tracked:

INFO_MERGE_IS_COMPLETE 0x43330100
Meaning: The merge operation was successfully completed.
Severity: Informational (0x4 prefix)
Context: Logged when a date log merge completes without errors.
Action: No action required; this is a successful operation notification.

Error Codes

The following error codes are returned by Date Log library functions when operations fail. All error codes have the format 0xC333XXXX (Error severity + Library facility).

Date Validation Errors

ERR_DATE_EARLIER_BASE 0xC3330400
Meaning: The provided date is earlier than the start date.
Context: Occurs when a date item predates the beginning of a date range or log.
Typical Causes:
  • Date is before the minimum allowed date in the collection
  • Range operation with inverted date boundaries
Resolution: Verify that the date parameter is within the valid range.
ERR_DATE_IS_FUTURE_DATE 0xC3330401
Meaning: The provided date is a future date (after today).
Context: Historical date logs cannot contain future dates by design.
Typical Causes:
  • Operation attempts to load dates beyond the current system date
  • Date range extends into the future
Resolution: Use dates up to and including today's date.
ERR_DATE_IS_HOLIDAY 0xC3330402
Meaning: The examined date is a holiday or weekend day.
Context: Market trading dates cannot be weekends or market holidays.
Typical Causes:
  • Date falls on Saturday (6) or Sunday (0)
  • Date is in the market holidays collection
Resolution: Select an adjacent market trading day (Monday-Friday, non-holiday).
ERR_DATE_NO_COVERED 0xC3330422
Meaning: The date is not covered by the holidays collection.
Context: The date range query exceeds the bounds of known holiday definitions.
Typical Causes:
  • Query date range extends beyond holiday list coverage
  • Holidays handle not properly initialized with full calendar data
Resolution: Ensure holidays are loaded for the required date range.

Date Item Errors

ERR_DATEITEM_NOT_FOUND 0xC3330405
Meaning: A date item was not found in the search performed.
Context: Search by GUID, date, or handle returned no match.
Typical Causes:
  • Item does not exist in the collection
  • Incorrect search parameters
Resolution: Verify the date item exists in the collection before searching.
ERR_NEXT_DATEITEM_NOT_FOUND 0xC3330416
Meaning: The next date item was not found.
Context: Navigation attempt to next date item at end of collection.
Resolution: Check if current item is the last item before calling next.
ERR_PREV_DATEITEM_NOT_FOUND 0xC3330417
Meaning: The previous date item was not found.
Context: Navigation attempt to previous date item at start of collection.
Resolution: Check if current item is the first item before calling previous.
ERR_DATEITEM_BAD_IDX 0xC3330414
Meaning: The location data for the date item is invalid.
Context: Internal file offset or index is corrupted or out of bounds.
Resolution: Reload date log from file or reinitialize collection.
ERR_DATEITEM_BAD_NUMBER 0xC3330415
Meaning: The item number for the date item is invalid.
Context: Sequential numbering in the collection is corrupted.
Resolution: Verify collection integrity or reload from backup.
ERR_DATEITEM_NO_COPY 0xC3330418
Meaning: The date item was not copied to the date log handle.
Context: Insertion of a date item into a collection failed.
Typical Causes:
  • Invalid date item structure
  • Collection full or corrupted
Resolution: Verify the date item values and collection state.

Handle and Merge Errors

ERR_INVALID_DATELOG_HANDLE 0xC3330406
Meaning: The date log or range handle is invalid.
Context: Handle validation failed or handle was already closed.
Typical Causes:
  • NULL handle passed
  • Handle already freed or corrupted
  • Wrong handle type for operation
Resolution: Verify handle is valid and correct type before use.
ERR_INVALID_HOLIDAY_HANDLE 0xC3330407
Meaning: The holidays handle is invalid.
Context: Holidays handle validation failed or initialization incomplete.
Resolution: Ensure holidays are properly loaded before date log operations.
ERR_BAD_HANDLE_TYPE 0xC3330421
Meaning: The handle type value is invalid.
Context: DateHandleType parameter is not one of: HandleIsForDatelog, HandleIsForRange, HandleIsForHolidays.
Resolution: Use correct DateHandleType enum value.
ERR_DATELOG_MERGE_GAP 0xC3330403
Meaning: There is a gap between the two merging date logs.
Context: Source and destination ranges do not overlap or are not contiguous.
Resolution: Ensure date ranges touch or overlap at boundaries for merge.
ERR_DATELOG_ZERO_GAP 0xC3330412
Meaning: The gap between start and end dates is zero or negative.
Context: Range generation or merge requires positive gap between dates.
Resolution: Ensure end date is after start date.
ERR_NOMERGE_BYFLAG 0xC3330404
Meaning: Date logs cannot be merged due to flag configuration.
Context: Source is contained within destination and flags favor destination.
Resolution: Use DATE_RANGE_MERGE_FAVOR_SOURCE flag or ensure proper overlap.
ERR_DATEITEM_START_NO_MATCH 0xC3330408
Meaning: Start date items do not match for merge.
Context: Source and destination ranges have different starting dates.
Resolution: Align date ranges before merge or use appropriate merge strategy.
ERR_DATEITEM_END_NO_MATCH 0xC3330409
Meaning: End date items do not match for merge.
Context: Source and destination ranges have different ending dates.
Resolution: Extend or trim ranges to match endpoints.
ERR_DATEITEM_FINAL_NO_MATCH 0xC3330410
Meaning: Final date items do not match after merge.
Context: Merge completed but verification found inconsistency.
Resolution: Retry merge or investigate data integrity.
ERR_NO_NEXT_MARKET_DATE 0xC3330411
Meaning: The compared date is not the next market day.
Context: IsNextMarketDay validation failed.
Resolution: Verify dates are sequential market days.

Capacity and Size Errors

ERR_MAX_DATELOG_REACHED 0xC3330413
Meaning: The date log exceeds maximum allowed size.
Context: Collection or gap size exceeds DATE_LOG_MAX constant.
Maximum Size: 0x591C8 (370,120) date items
Resolution: Use smaller date ranges or split into multiple logs.
ERR_DATELOG_LENGTH_MAX 0xC3330419
Meaning: Current date log length exceeds limit.
Context: Existing collection size has reached maximum capacity.
Resolution: Archive existing log and create new one for additional dates.

Configuration and System Errors

ERR_DATELOG_NO_HOLIDAYS 0xC3330420
Meaning: The holidays handle is invalid inside the date log.
Context: Date log initialized without valid holidays reference.
Resolution: Initialize date log with valid holidays handle.
ERR_DATE_RECORDS_BAD_LENGTH 0xC3330424
Meaning: The date record to be written has invalid length.
Context: File write operation has incorrect data size.
Expected Length: 48 bytes per record
Resolution: Verify record structure and alignment.
ERR_DATE_LOG_PENDING_IO 0xC3330430
Meaning: The date log handle is busy; not available at this time.
Context: Another operation holds locks on the handle.
Typical Causes:
  • Concurrent merge operation in progress
  • File I/O or lock acquisition timeout
  • Mutex wait timeout (30-second default)
Resolution: Wait briefly and retry, or reduce concurrent access.

Recovery and Restoration Errors

ERR_MERGE_NO_COMPLETE 0xC3330423
Meaning: The merge operation did not complete successfully.
Context: Merge process was interrupted or encountered unrecoverable error.
Resolution: Retry merge or restore from backup state.
ERR_DATE_FILE_RESTORE_FAILED 0xC3330431
Severity: Warning (merge operation may have failed recovery)
Meaning: Failed to restore file to original state after failure.
Context: Merge failed and backup restoration also failed.
Impact: File may be in inconsistent state; recommend verification.
Resolution: Restore from offline backup or verify file integrity.
ERR_DATE_LOG_RESTORE_FAILED 0xC3330432
Severity: Warning (merge operation may have failed recovery)
Meaning: Failed to restore date log collection to original state.
Context: Merge failed and in-memory array restoration also failed.
Impact: Date log context marked invalid; handle unusable.
Resolution: Close handle and reinitialize from data source.

Usage Examples

Basic Error Checking

Example 1: Simple Success Check
// Most common usage pattern
HRESULT hr = InitializeDateItem(hDateLog, &fileTime, NULL, &hDateItem);

if (SUCCEEDED(hr)) {
    // Operation succeeded, use hDateItem
    printf("Date item created successfully\n");
} else {
    // Operation failed, log error code
    printf("Failed to create date item: 0x%08X\n", hr);
}

// Clean up
if (hDateItem != NULL) {
    FreeDateItem(hDateItem);
}

Error Code Extraction

Example 2: Extracting HRESULT Components
HRESULT hr = MergeDateLogHandle(hDest, hSource, dwFlags);

if (FAILED(hr)) {
    // Extract components
    DWORD dwSeverity = HRESULT_SEVERITY(hr);
    DWORD dwFacility = HRESULT_FACILITY(hr);
    DWORD dwCode = HRESULT_CODE(hr);
    DWORD dwCustomer = HRESULT_CUSTOMER(hr);

    printf("Error 0x%08X:\n", hr);
    printf("  Severity: 0x%X\n", dwSeverity);
    printf("  Customer: %s\n", dwCustomer ? "Library-defined" : "System-defined");
    printf("  Facility: 0x%X\n", dwFacility);
    printf("  Code: 0x%X\n", dwCode);

    // Handle specific errors
    switch (hr) {
    case ERR_DATE_LOG_PENDING_IO:
        printf("Date log is busy, retrying...\n");
        Sleep(100);
        // Retry operation
        break;
    case ERR_DATELOG_ZERO_GAP:
        printf("Invalid date range (zero or negative gap)\n");
        break;
    case ERR_INVALID_DATELOG_HANDLE:
        printf("Invalid handle provided\n");
        break;
    default:
        printf("Unknown error occurred\n");
        break;
    }
}

Specific Error Handling

Example 3: Targeted Error Handling
HRESULT hr = InitializeDateItem(hDateLog, &ft, NULL, &hItem);

if (SUCCEEDED(hr)) {
    printf("Date item created\n");
} else if (hr == ERR_DATE_IS_HOLIDAY) {
    // Special handling for holidays
    printf("Selected date is a holiday/weekend.\n");
    printf("Please select a market trading day.\n");
    
    // Find next valid market day
    FILETIME ftNext = ft;
    // Add logic to increment to next business day
    
} else if (hr == ERR_DATE_IS_FUTURE_DATE) {
    printf("ERROR: Cannot use future dates\n");
    
} else if (hr == ERR_INVALID_DATELOG_HANDLE) {
    printf("ERROR: Invalid date log handle\n");
    printf("Reinitialize handle and retry\n");
    
} else {
    printf("Unexpected error: 0x%08X\n", hr);
}

FormatMessage Integration

Overview

Error codes defined in this library support the Windows FormatMessage API when the library is properly registered with the system's message resource files. This allows human-readable error messages to be retrieved dynamically.

Message Resource Requirements

For FormatMessage integration to work, the library must:

Current Status: The MDTS Date Log library currently defines error codes but may not have compiled message resources. For user-defined friendly messages, implement a custom error mapping function as shown in the examples below.

Basic FormatMessage Usage

Example 4: FormatMessage with Library Errors
#include 
#include 

// Custom error message mapping function
const char* GetDateLogErrorMessage(HRESULT hr) {
    switch (hr) {
    case S_OK:
        return "Operation completed successfully";
    case ERR_DATE_IS_HOLIDAY:
        return "The selected date is a holiday or weekend";
    case ERR_DATE_EARLIER_BASE:
        return "The date is earlier than the start date";
    case ERR_INVALID_DATELOG_HANDLE:
        return "Invalid date log handle";
    case ERR_DATELOG_ZERO_GAP:
        return "Zero or negative gap between dates";
    case ERR_MAX_DATELOG_REACHED:
        return "Date log exceeds maximum size";
    case ERR_DATE_LOG_PENDING_IO:
        return "Date log is busy; operation pending";
    default:
        return "Unknown error occurred";
    }
}

// Usage example
int main() {
    HRESULT hr = InitializeDateItem(hDateLog, &ft, NULL, &hItem);
    
    if (FAILED(hr)) {
        const char* pszMsg = GetDateLogErrorMessage(hr);
        printf("ERROR (0x%08X): %s\n", hr, pszMsg);
        return 1;
    }
    
    return 0;
}

Advanced: System Error Code Integration

Example 5: Hybrid Error Message Resolution
// Combine library and system error messages
void PrintDetailedError(HRESULT hr) {
    LPVOID lpMsgBuf = NULL;
    DWORD dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM;
    DWORD dwFacility = HRESULT_FACILITY(hr);
    
    printf("===== Error Report =====\n");
    printf("Error Code: 0x%08X\n", hr);
    printf("Severity: %s\n", HRESULT_SEVERITY(hr) >= 2 ? "ERROR" : "INFO");
    printf("Facility: 0x%X (%s)\n", dwFacility,
        (dwFacility == 0x333) ? "FACILITY_THISLIB" : 
        (dwFacility == 0xFFF) ? "FACILITY_APPLICATION" :
        "FACILITY_SYSTEM");
    printf("Error Code: 0x%X\n", HRESULT_CODE(hr));
    
    // Try system error translation first
    if (FormatMessageA(dwFlags, NULL, hr, 
                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                       (LPSTR)&lpMsgBuf, 0, NULL)) {
        printf("System Message: %s\n", (const char*)lpMsgBuf);
        LocalFree(lpMsgBuf);
    } else {
        // Fall back to custom messages
        printf("Message: %s\n", GetDateLogErrorMessage(hr));
    }
    
    printf("=======================\n");
}

// Example call
int main() {
    HRESULT hr = MergeDateLogHandle(hDest, hSource, dwFlags);
    if (FAILED(hr)) {
        PrintDetailedError(hr);
    }
    return 0;
}

Error Logging Pattern

Example 6: Comprehensive Error Logging
// Production-quality error logging
BOOL LogDateLogError(HRESULT hr, const char* pszOperation) {
    FILE* pFile = fopen("datelog_errors.log", "a");
    if (pFile == NULL) return FALSE;
    
    SYSTEMTIME st;
    GetLocalTime(&st);
    
    fprintf(pFile, "[%04d-%02d-%02d %02d:%02d:%02d] ",
        st.wYear, st.wMonth, st.wDay,
        st.wHour, st.wMinute, st.wSecond);
    
    fprintf(pFile, "OPERATION: %s\n", pszOperation);
    fprintf(pFile, "ERROR CODE: 0x%08X\n", hr);
    fprintf(pFile, "SEVERITY: %d\n", HRESULT_SEVERITY(hr));
    fprintf(pFile, "FACILITY: 0x%X\n", HRESULT_FACILITY(hr));
    fprintf(pFile, "CODE: 0x%X\n", HRESULT_CODE(hr));
    fprintf(pFile, "MESSAGE: %s\n", GetDateLogErrorMessage(hr));
    fprintf(pFile, "---\n");
    
    fclose(pFile);
    return TRUE;
}

// Usage
HRESULT hr = LoadDateLogHandle(pFileInfo, NULL, NULL, hDateLog, NULL, dwFlags);
if (FAILED(hr)) {
    LogDateLogError(hr, "LoadDateLogHandle");
}

Registering Message DLL (Advanced)

Registry Entry for FormatMessage (if implemented)
// Windows Registry path for message DLL registration
// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\MDTS_DateLog
// 
// Registry entries to add:
// EventMessageFile: C:\Program Files\MDTS\mdts_datelog.dll
// TypesSupported: 7 (Success, Error, Warning)
//
// PowerShell command to register:
// New-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\Application\MDTS_DateLog" -Force
// Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\Application\MDTS_DateLog" `
//                   -Name "EventMessageFile" -Value "C:\Program Files\MDTS\mdts_datelog.dll"
// Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\Application\MDTS_DateLog" `
//                   -Name "TypesSupported" -Value 7

Using FormatMessage After Registration

Example 7: FormatMessage with Registered DLL
// This will work only if the DLL is registered
DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER;
LPVOID lpMsgBuf = NULL;
HRESULT hr = InitializeDateItem(hDateLog, &ft, NULL, &hItem);

if (FAILED(hr)) {
    // FormatMessage can now find the message in the registered DLL
    if (FormatMessageA(dwFlags, NULL, hr,
                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                       (LPSTR)&lpMsgBuf, 0, NULL)) {
        fprintf(stderr, "ERROR: %s\n", (const char*)lpMsgBuf);
        LocalFree(lpMsgBuf);
    } else {
        // Fallback to custom message
        fprintf(stderr, "ERROR (0x%08X): %s\n", hr, 
                GetDateLogErrorMessage(hr));
    }
}

Quick Reference: Error Code Summary

Error Code Value Category Severity
INFO_MERGE_IS_COMPLETE 0x43330100 Informational Success
ERR_DATE_EARLIER_BASE 0xC3330400 Date Validation Error
ERR_DATE_IS_FUTURE_DATE 0xC3330401 Date Validation Error
ERR_DATE_IS_HOLIDAY 0xC3330402 Date Validation Error
ERR_DATELOG_MERGE_GAP 0xC3330403 Merge Error
ERR_NOMERGE_BYFLAG 0xC3330404 Merge Error
ERR_DATEITEM_NOT_FOUND 0xC3330405 Date Item Error
ERR_INVALID_DATELOG_HANDLE 0xC3330406 Handle Error
ERR_INVALID_HOLIDAY_HANDLE 0xC3330407 Handle Error
ERR_DATELOG_ZERO_GAP 0xC3330412 Range Error
ERR_MAX_DATELOG_REACHED 0xC3330413 Capacity Error
ERR_DATE_LOG_PENDING_IO 0xC3330430 I/O Error