API Errors In Plain English

From HashVB
Jump to: navigation, search

Sometimes it will be necessary to get the error description out of an API error code. Usually these are extremely nondescript and totally useless, but occasionally they come in handy. In such a case, it is very useful to have a simple and quick piece of code that you can just put in a module to get your error descriptions. The following code will do just this:

   Option Explicit
   Const LANG_NEUTRAL = &H0
   Const ERROR_BAD_USERNAME = 2202&
   Private Declare Function GetLastError Lib "kernel32" () As Long
   Private Declare Sub SetLastError Lib "kernel32" (ByVal dwErrCode As Long)
   Private Declare Function FormatMessage Lib "kernel32" Alias "FormatMessageA" (ByVal dwFlags As Long, lpSource As Any, ByVal dwMessageId As Long, ByVal dwLanguageId As Long, ByVal lpBuffer As String, ByVal nSize As Long, Arguments As Long) As Long
   Public Function GetError(error As Long) As String
       Dim Buffer As String
       'Create a string buffer
       Buffer = String(256, Chr(0))
       'Format the message string
       FormatMessage FORMAT_MESSAGE_FROM_SYSTEM, ByVal 0&, error, LANG_NEUTRAL, Buffer, 256, ByVal 0&
       GetError = Buffer
   End Function

The GetError() function will return the error description as a string for you to log or output to the immediate window, or whatever you will.