Testing

webTiger Logo Wide

Resolving Windows API Error Codes to Messages

Windows Logo

Whenever you are working with the Windows API, there is a better than average chance that you’ll have to deal with a Windows API Error Code. Within your code it is useful to be able to resolve this value to a more meaningful error message and, fortunately, the Windows API includes functionality to do just that.

First you will need to define some API constants and DLL imports:

namespace My.WinApi.Utilities
{
    public class ApiErrorTranslator
    {

        public const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
        public const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
        public const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;

        [DllImport("kernel32.dll")]
        public static extern uint FormatMessage(
            uint dwFlags, [In] byte[] lpSource, uint dwMessageId, uint dwLanguageId,
            out string lpBuffer, uint nSize, IntPtr Arguments);
    }
}Code language: C# (cs)

Now all you need to do is use the FormatMessage function to retrieve a meaningful error message for your code:

public string GetErrorMessage(int apiErrorCode)
{
    try
    {
        const uint minimumCharCount = 0;
        string messageBuffer = "";

        if (ApiErrorTranslator.FormatMessage(
            ApiErrorTranslator.FORMAT_MESSAGE_ALLOCATE_BUFFER |
            ApiErrorTranslator.FORMAT_MESSAGE_FROM_SYSTEM | 
            ApiErrorTranslator.FORMAT_MESSAGE_IGNORE_INSERTS, 
            null,
            (uint)apiErrorCode, 0, // auto-determine language
            out messageBuffer, 
            minimumCharCount, 
            new IntPtr(0)) == 0)
        {
            // The FormatMessage() call failed so just return the supplied 
            // error code
            return string.Format(
                "An error occurred (error code: {0}), but the error message " + 
                "could not be decoded", 
                apiErrorCode);
        }

        // Return the message information
        if (messageBuffer == "")
        {
            return string.Format("API error code: {0}", apiErrorCode);
        }
        else
        {
            return messageBuffer;
        }
    }
    catch
    {
        // Something went wrong, so just return the supplied error code.
        return string.Format("API error code: {0}", apiErrorCode);
    }
}Code language: C# (cs)