SDL: hidapi: improved error handling

From 211054d9db71df171b281f0ab14fd862613cde0e Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Sat, 27 May 2023 08:33:48 -0700
Subject: [PATCH] hidapi: improved error handling

---
 src/hidapi/linux/hid.c   |  6 +++++-
 src/hidapi/mac/hid.c     |  6 +++++-
 src/hidapi/windows/hid.c | 23 +++++++++++++++--------
 3 files changed, 25 insertions(+), 10 deletions(-)

diff --git a/src/hidapi/linux/hid.c b/src/hidapi/linux/hid.c
index 7274aeff96b7..cc0edbaf7838 100644
--- a/src/hidapi/linux/hid.c
+++ b/src/hidapi/linux/hid.c
@@ -133,7 +133,11 @@ static void register_error_str(wchar_t **error_str, const char *msg)
 	free(*error_str);
 #ifdef HIDAPI_USING_SDL_RUNTIME
 	/* Thread-safe error handling */
-	SDL_SetError("%s", msg);
+	if (msg) {
+		SDL_SetError("%s", msg);
+	} else {
+		SDL_ClearError();
+	}
 #else
 	*error_str = utf8_to_wchar_t(msg);
 #endif
diff --git a/src/hidapi/mac/hid.c b/src/hidapi/mac/hid.c
index 20e898e7e0b5..d646f7699e4c 100644
--- a/src/hidapi/mac/hid.c
+++ b/src/hidapi/mac/hid.c
@@ -246,7 +246,11 @@ static void register_error_str(wchar_t **error_str, const char *msg)
 	free(*error_str);
 #ifdef HIDAPI_USING_SDL_RUNTIME
 	/* Thread-safe error handling */
-	SDL_SetError("%s", msg);
+	if (msg) {
+		SDL_SetError("%s", msg);
+	} else {
+		SDL_ClearError();
+	}
 #else
 	*error_str = utf8_to_wchar_t(msg);
 #endif
diff --git a/src/hidapi/windows/hid.c b/src/hidapi/windows/hid.c
index 68e2e8ad07e7..13e59c377286 100644
--- a/src/hidapi/windows/hid.c
+++ b/src/hidapi/windows/hid.c
@@ -258,6 +258,11 @@ static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR
 	free(*error_buffer);
 	*error_buffer = NULL;
 
+#ifdef HIDAPI_USING_SDL_RUNTIME
+	/* Thread-safe error handling */
+	SDL_ClearError();
+#endif
+
 	/* Only clear out error messages if NULL is passed into op */
 	if (!op) {
 		return;
@@ -334,18 +339,20 @@ static void register_string_error_to_buffer(wchar_t **error_buffer, const WCHAR
 	free(*error_buffer);
 	*error_buffer = NULL;
 
-	if (string_error) {
 #ifdef HIDAPI_USING_SDL_RUNTIME
-		/* Thread-safe error handling */
-		char *error_utf8 = SDL_iconv_wchar_utf8(string_error);
-		if (error_utf8) {
-			SDL_SetError("%s", error_utf8);
-			SDL_free(error_utf8);
-		}
+	/* Thread-safe error handling */
+	char *error_utf8 = string_error ? SDL_iconv_wchar_utf8(string_error) : NULL;
+	if (error_utf8) {
+		SDL_SetError("%s", error_utf8);
+		SDL_free(error_utf8);
+	} else {
+		SDL_ClearError();
+	}
 #else
+	if (string_error) {
 		*error_buffer = _wcsdup(string_error);
-#endif
 	}
+#endif /* HIDAPI_USING_SDL_RUNTIME */
 }
 
 #if defined(__GNUC__)