Windows error handling

Post your working scripts, libraries and tools for AHK v1.1 and older
User avatar
Onimuru
Posts: 107
Joined: 08 Sep 2018, 18:35
Contact:

Windows error handling

Post by Onimuru » 28 Apr 2021, 03:49

I have been using a lot of windows functions and it was necessary to have some descriptive errors and so I made a wrapper for FormatMessage (https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessage). Perhaps some of you will find this useful:

Code: Select all

;* FormatMessage(messageID)
FormatMessage(messageID) {
	if (!length := DllCall("Kernel32\FormatMessage", "UInt", 0x1100, "Ptr", 0, "UInt", messageID, "UInt", 0, "Ptr*", buffer := 0, "UInt", 0, "Ptr", 0, "UInt")) {
		return (FormatMessage(DllCall("Kernel32\GetLastError")))
	}

	return (StrGet(buffer, length - 2), DllCall("Kernel32\LocalFree", "Ptr", buffer, "Ptr"))
}
Here's an example of how I would typically use it:

Code: Select all

if (!DllCall("GetConsoleScreenBufferInfo", "Ptr", 0, "Ptr", 0, "UInt")) {
	throw (Exception(Format("0x{:U}", DllCall("msvcrt\_i64tow", "Int64", A_LastError, "Ptr*", 0, "UInt", 16, "Str")), -1, FormatMessage(A_LastError)))
}
There is also this tool by Microsoft that is super useful: https://docs.microsoft.com/en-us/windows/win32/debug/system-error-code-lookup-tool
Last edited by Onimuru on 04 May 2021, 11:31, edited 2 times in total.

User avatar
SKAN
Posts: 1551
Joined: 29 Sep 2013, 16:58

Re: Windows error handling

Post by SKAN » 03 May 2021, 18:38

Hi @Onimuru

There is a resource leak in your function. You are not freeing the system allocated buffer.

Code: Select all

#NoEnv
#Warn
#SingleInstance, Force

FileOpen("A:\non-existent-path\non-existent.file", "r")
Err := A_LastError

DllCall("Kernel32.dll\FormatMessage", "Int",0x1100, "Ptr",0, "Int",Err, "Int",0, "PtrP",hMem:=0, "Int",0, "Ptr",0)
ErrMsg  := StrGet(hMem)
hMem := DllCall("Kernel32.dll\LocalFree", "Ptr",hMem, "Ptr")
MsgBox % ErrMsg

User avatar
Onimuru
Posts: 107
Joined: 08 Sep 2018, 18:35
Contact:

Re: Windows error handling

Post by Onimuru » 04 May 2021, 09:18

@SKAN

Many thanks.

Post Reply

Return to “Scripts and Functions (v1)”