Commit b261c286 by Jonathan Thomas

Improve error messages for OpenAI and CreatureChat API

parent ec7d966f
......@@ -9,6 +9,10 @@ All notable changes to **CreatureChat** are documented in this file. The format
### Added
- New automated deployments for Modrinth and CurseForge (GitLab CI Pipeline)
### Fixed
- Parse OpenAI JSON error messages, to display a more readable error message
- Remove quotes from CreatureChat API error messages
## [1.0.4] - 2024-05-15
### Added
......
package com.owlmaddie.chat;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.owlmaddie.commands.ConfigurationHandler;
import com.owlmaddie.json.ChatGPTResponse;
import com.owlmaddie.network.ServerPackets;
......@@ -63,6 +64,47 @@ public class ChatGPTRequest {
}
}
public static String removeQuotes(String str) {
if (str != null && str.length() > 1 && str.startsWith("\"") && str.endsWith("\"")) {
return str.substring(1, str.length() - 1);
}
return str;
}
// Class to represent the error response structure
public static class ErrorResponse {
Error error;
static class Error {
String message;
String type;
String code;
}
}
public static String parseAndLogErrorResponse(String errorResponse) {
try {
Gson gson = new Gson();
ErrorResponse response = gson.fromJson(errorResponse, ErrorResponse.class);
if (response.error != null) {
LOGGER.error("Error Message: " + response.error.message);
LOGGER.error("Error Type: " + response.error.type);
LOGGER.error("Error Code: " + response.error.code);
return response.error.message;
} else {
LOGGER.error("Unknown error response: " + errorResponse);
return "Unknown";
}
} catch (JsonSyntaxException e) {
LOGGER.warn("Failed to parse error response as JSON, falling back to plain text");
LOGGER.error("Error response: " + errorResponse);
} catch (Exception e) {
LOGGER.error("Failed to parse error response", e);
}
return removeQuotes(errorResponse);
}
// This method should be called in an appropriate context where ResourceManager is available
public static String loadPromptFromResource(ResourceManager resourceManager, String filePath) {
Identifier fileIdentifier = new Identifier("creaturechat", filePath);
......@@ -173,8 +215,12 @@ public class ChatGPTRequest {
while ((errorLine = errorReader.readLine()) != null) {
errorResponse.append(errorLine.trim());
}
LOGGER.error("Error response from API: " + errorResponse);
lastErrorMessage = errorResponse.toString();
// Parse and log the error response using Gson
String cleanError = parseAndLogErrorResponse(errorResponse.toString());
lastErrorMessage = cleanError;
} catch (Exception e) {
LOGGER.error("Failed to read error response", e);
}
return null;
} else {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment