⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 windowserrortext.cpp

📁 发送邮件
💻 CPP
字号:
/*=========================================================================== 
    (c) Copyright 1998-2000, Emmanuel KARTMANN, all rights reserved                 
  =========================================================================== 
    File           : WindowsErrorText.cpp
    $Header: $
    Author         : Emmanuel KARTMANN
    Creation       : Monday 11/15/98 11:44:48 PM
    Remake         : 
  ------------------------------- Description ------------------------------- 

           Implementation of the WindowsGetErrorText function.

  ------------------------------ Modifications ------------------------------ 
    $Log: $  
  =========================================================================== 
*/


#include "stdafx.h"

// We need this for function InternetGetLastResponseInfo (maps extended Inet error code to a text)
#include <wininet.h>
#pragma comment(lib, "wininet.lib")

typedef struct _WinsockErrorMapping {
    DWORD dwCode;
    LPCTSTR lpszMessage;
} WinsockErrorMapping;

WinsockErrorMapping lpWinsockErrorMappings[] = {
    {WSAEINTR, "WSAEINTR - Interrupted"},
    {WSAEBADF, "WSAEBADF - Bad file number"},
    {WSAEFAULT,   "WSAEFAULT - Bad address"},
    {WSAEINVAL,          "WSAEINVAL - Invalid argument"},
    {WSAEMFILE,          "WSAEMFILE - Too many open files"},
    /* *    Windows Sockets definitions of regular Berkeley error constants */
    {WSAEWOULDBLOCK,   "WSAEWOULDBLOCK - Socket marked as non-blocking"},
    {WSAEINPROGRESS,     "WSAEINPROGRESS - Blocking call in progress"},
    {WSAEALREADY,        "WSAEALREADY - Command already completed"},
    {WSAENOTSOCK,        "WSAENOTSOCK - Descriptor is not a socket"},
    {WSAEDESTADDRREQ,    "WSAEDESTADDRREQ - Destination address required"},
    {WSAEMSGSIZE,        "WSAEMSGSIZE - Data size too large"},
    {WSAEPROTOTYPE,      "WSAEPROTOTYPE - Protocol is of wrong type for this socket"},
    {WSAENOPROTOOPT,     "WSAENOPROTOOPT - Protocol option not supported for this socket type"},
    {WSAEPROTONOSUPPORT, "WSAEPROTONOSUPPORT - Protocol is not supported"},
    {WSAESOCKTNOSUPPORT, "WSAESOCKTNOSUPPORT - Socket type not supported by this address family"},
    {WSAEOPNOTSUPP,      "WSAEOPNOTSUPP - Option not supported"},
    {WSAEPFNOSUPPORT,    "WSAEPFNOSUPPORT - Protocol family not supported"},
    {WSAEAFNOSUPPORT,    "WSAEAFNOSUPPORT - Address family not supported by this protocol"},
    {WSAEADDRINUSE,      "WSAEADDRINUSE - Address is in use"},
    {WSAEADDRNOTAVAIL,   "WSAEADDRNOTAVAIL - Address not available from local machine"},
    {WSAENETDOWN,        "WSAENETDOWN - Network subsystem is down"},
    {WSAENETUNREACH,     "WSAENETUNREACH - Network cannot be reached"},
    {WSAENETRESET,       "WSAENETRESET - Connection has been dropped"},
    {WSAECONNABORTED,    "WSAECONNABORTED - Software caused connection abort"},
    {WSAECONNRESET,      "WSAECONNRESET - Connection reset by peer"},
    {WSAENOBUFS,         "WSAENOBUFS - No buffer space available"},
    {WSAEISCONN,         "WSAEISCONN - Socket is already connected"},
    {WSAENOTCONN,        "WSAENOTCONN - Socket is not connected"},
    {WSAESHUTDOWN,       "WSAESHUTDOWN - Socket has been shut down"},
    {WSAETOOMANYREFS,    "WSAETOOMANYREFS - Too many references: cannot splice"},
    {WSAETIMEDOUT,       "WSAETIMEDOUT - Command timed out"},
    {WSAECONNREFUSED,    "WSAECONNREFUSED - Connection refused"},
    {WSAELOOP,           "WSAELOOP - Too many levels of symbolic links"},
    {WSAENAMETOOLONG,    "WSAENAMETOOLONG - File name too long"},
    {WSAEHOSTDOWN,       "WSAEHOSTDOWN - Host is down"},
    {WSAEHOSTUNREACH,    "WSAEHOSTUNREACH - No route to host"},
    {WSAENOTEMPTY,       "WSAENOTEMPTY - "},
    {WSAEPROCLIM,        "WSAEPROCLIM - Too many processes"},
    {WSAEUSERS,          "WSAEUSERS - "},
    {WSAEDQUOT,          "WSAEDQUOT - "},
    {WSAESTALE,          "WSAESTALE - "},
    {WSAEREMOTE,         "WSAEREMOTE - "},
    /* *    Extended Windows Sockets error constant definitions */
    {WSASYSNOTREADY,     "WSASYSNOTREADY - Network subsystem not ready"},
    {WSAVERNOTSUPPORTED, "WSAVERNOTSUPPORTED - Version not supported"},
    {WSANOTINITIALISED,  "WSANOTINITIALISED - WSAStartup() has not been successfully called"},
    /* *    Other error constants. */
    {WSAHOST_NOT_FOUND,  "WSAHOST_NOT_FOUND - Host not found"},
    {WSATRY_AGAIN,       "WSATRY_AGAIN - Host not found or SERVERFAIL"},
    {WSANO_RECOVERY,     "WSANO_RECOVERY - Non-recoverable error"},
    {WSANO_DATA,         "WSANO_DATA - (or WSANO_ADDRESS) - No data record of requested type"},
    {-1, NULL}
};

DWORD WindowsSocketGetErrorText(DWORD dwErrorCode, LPTSTR *lplpszTemp)
{
    DWORD dwReturnCode = 0;

    if (!lplpszTemp) {
        return(0);
    }
    if (*lplpszTemp) {
        LocalFree(*lplpszTemp);
    }
    *lplpszTemp = NULL;

    // Winsock errors are above 10000 (WSABASEERR)
    if (dwErrorCode > WSABASEERR) {
        for (int i=0; 
             lpWinsockErrorMappings[i].dwCode!=(DWORD)-1 &&
             lpWinsockErrorMappings[i].lpszMessage != NULL; 
             i++) {
            if (lpWinsockErrorMappings[i].dwCode == dwErrorCode) {
                break;
            }
        }
        if (lpWinsockErrorMappings[i].lpszMessage != NULL) {
            // Found message: allocate and copy it
            size_t nMessageLength = strlen(lpWinsockErrorMappings[i].lpszMessage);
            *lplpszTemp = (LPTSTR)LocalAlloc(0, nMessageLength+1);
            if (*lplpszTemp) {
                strcpy(*lplpszTemp, lpWinsockErrorMappings[i].lpszMessage);
                dwReturnCode = nMessageLength;
            }
        }
    }

    return(dwReturnCode);
}

LPTSTR WindowsGetErrorText(DWORD dwErrorCode, LPTSTR lpszBuf, DWORD dwSize) 
{
    LPTSTR lpszTemp = 0;

    DWORD dwRet =	::FormatMessage(
						FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ARGUMENT_ARRAY,
						0,
						dwErrorCode,
						MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
						(LPTSTR)&lpszTemp,
						0,
						0
					);

    if( !dwRet || (dwSize < dwRet+14) ) {
        if(lpszTemp) {
            LocalFree(HLOCAL(lpszTemp));
            lpszTemp = NULL;
        }
        lpszBuf[0] = TEXT('\0');
        // Empty string: couldn't map message code to a text!
        // Try in winsock
        dwRet = WindowsSocketGetErrorText(dwErrorCode, &lpszTemp);
        if (!dwRet) {
            // Try in other modules (resources are in other DLLs...)
            TCHAR *lpszOtherModuleNames[] = {
                "wininet.dll",
                // The module below cannot be used to map error code to error message: it's garbled!!!
                //"wsock32.dll", 
                "mqutil.dll",
                NULL
            };
            int nCurrentModule = 0;
            while (lpszOtherModuleNames[nCurrentModule]) {
                HMODULE hModule = GetModuleHandle(lpszOtherModuleNames[nCurrentModule]);
                dwRet=0;

                if (hModule) {
                    dwRet = FormatMessage(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
                                          hModule,
                                          dwErrorCode, 
                                          0,
                                          (LPTSTR)&lpszTemp,
                                          0,
                                          NULL);
                    if (dwRet) {
                        // Found message stop loop
                        break;
                    }
                }
                nCurrentModule++;
            }
        }

        if (!dwRet) {

            // Nothing either: Show the code anyway
            sprintf(lpszBuf, "Error Code 0x%X (%d)", dwErrorCode, dwErrorCode);

        } else {
            _tcscpy(lpszBuf, lpszTemp);
        }

        // Still Try in EXTENDED INET ERROR
        if (HRESULT_CODE(dwErrorCode) == ERROR_INTERNET_EXTENDED_ERROR) {
            DWORD  dwIntError , dwLength = 0;
            // Try to fetch the error text length BEFORE allocating the buffer
            if (InternetGetLastResponseInfo(&dwIntError, NULL, &dwLength)) {
                if (dwLength) {
                    if ((lpszTemp = (TCHAR *) LocalAlloc( LPTR,  dwLength) ) ) {
                        if (!InternetGetLastResponseInfo(&dwIntError, (LPTSTR) lpszTemp, &dwLength)) {
                            // Can't map: keep the raw code
                            LocalFree(lpszTemp);
                            lpszTemp=NULL;
                        } else {
                            // Found extended error: copy it or add it to current error
                            _tcscat(lpszBuf, lpszTemp);
                        }
                    
                    }
                }
            } else {
                // Can't get extended error: try again with fixed-length buffer
                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
                    // Try to guess the buffer length
                    DWORD dwLength = 4096;
                    if ((lpszTemp = (TCHAR *) LocalAlloc( LPTR,  dwLength) ) ) {
                        if (!InternetGetLastResponseInfo(&dwIntError, (LPTSTR) lpszTemp, &dwLength)) {
                            // Can't map: keep the raw code
                            LocalFree(lpszTemp);
                            lpszTemp=NULL;
                        } else {
                            // Found extended error: copy it or add it to current error
                            _tcscat(lpszBuf, lpszTemp);
                        }
                    }
                }
            }
            
        }

    } else {
        lpszTemp[_tcsclen(lpszTemp)-2] = TEXT('\0');  //remove cr/nl characters
        _tcscpy(lpszBuf, lpszTemp);
    }

    if (lpszTemp) {
        LocalFree(lpszTemp);
        lpszTemp=NULL;
    }

    TRACE1("\n\nERROR: %s\n\n", lpszBuf);
    return lpszBuf;
}



⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -