API Errors In Plain English

From HashVB
Revision as of 10:50, 19 April 2006 by Wakjah (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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 FORMAT_MESSAGE_ALLOCATE_BUFFER = &H100
   Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000
   Const LANG_NEUTRAL = &H0
   Const SUBLANG_DEFAULT = &H1
   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.