Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,8 @@ libs/
# Local config overrides
config.local.json

# Sentry auth token (secret — never commit)
.sentry-auth-token

# Serena
.serena/
26 changes: 25 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

*No changes yet*
### Added

**Sentry Error Tracking Integration**
- Sentry SDK (v8.33.0) bundled for automatic error reporting to Sentry dashboard
- Non-blocking async event delivery — Sentry never impacts server performance
- All Sentry operations wrapped in try/catch — failures never crash the server
- Sentry config nested under `config/debug.json` → `"sentry"` section (no separate file)
- Auto-migration: existing `config/sentry.json` values are read into `debug.json` on first load, old file deleted
- DSN pre-configured with default — works out of the box
- Source context upload via Sentry Gradle plugin (stack traces show source code in Sentry)
- HyperFactions frames highlighted in stack traces via `addInAppInclude`
- New admin command: `/f admin sentry` — view status, enable/disable error reporting at runtime
- New admin command: `/f admin sentrytest` — sends a test error with stack trace to verify integration
- Sentry cleanly flushes pending events on server shutdown (2s timeout)
- Auth token stored in `.sentry-auth-token` file (gitignored) with env var fallback

**Global Error Handling via ErrorHandler**
- New `ErrorHandler` utility class — centralized error handling that logs to console AND reports to Sentry
- 6 static methods covering all error patterns: `report()`, `report(@Nullable)`, `wrapTask()`, `guard()`, `runSafely()` (2 overloads)
- ~190 `Logger.severe()` calls in catch blocks across ~50 files now route through ErrorHandler to Sentry
- Scheduled/timer tasks wrapped with `wrapTask()` — exceptions no longer silently kill scheduler threads
- CompletableFuture chains guarded with `guard()` — async errors no longer swallowed
- Shutdown sequence steps isolated with `runSafely()` — one failure doesn't skip remaining cleanup
- `WriteResult.Failure` storage errors (with `@Nullable Exception cause`) now report to Sentry
- Pre-init error buffering: errors during config/data loading (before Sentry initializes) are buffered and flushed once Sentry is ready, tagged with `pre_init: true`

## [0.10.2] - 2026-02-28

Expand Down
23 changes: 23 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ plugins {
id 'checkstyle'
id 'maven-publish'
id 'com.gradleup.shadow' version '9.3.1'
id 'io.sentry.jvm.gradle' version '6.1.0'
}

group = 'com.hyperfactions'
Expand Down Expand Up @@ -71,6 +72,9 @@ dependencies {
// JSON handling
implementation 'com.google.code.gson:gson:2.11.0'

// Sentry error tracking (bundled in shadow JAR)
implementation 'io.sentry:sentry:8.33.0'

// PlaceholderAPI Hytale (soft dependency - compileOnly)
compileOnly 'at.helpch:placeholderapi-hytale:1.0.4'

Expand Down Expand Up @@ -144,6 +148,7 @@ shadowJar {

// Relocate dependencies to avoid conflicts
relocate 'com.google.gson', 'com.hyperfactions.lib.gson'
relocate 'io.sentry', 'com.hyperfactions.lib.sentry'

// Don't minimize - it removes Gson's inner classes needed at runtime
}
Expand All @@ -168,6 +173,7 @@ tasks.withType(Checkstyle).configureEach {

build {
dependsOn shadowJar
finalizedBy tasks.matching { it.name == 'sentryUploadSourceBundleJava' }
}

tasks.withType(JavaCompile).configureEach {
Expand All @@ -194,6 +200,11 @@ tasks.named('compileJava') {
}
}

// Sentry tasks use the same generated sources dir as generateBuildInfo — declare dependencies
tasks.matching { it.name.startsWith('sentry') || it.name.startsWith('generateSentry') }.configureEach {
dependsOn 'generateBuildInfo'
}

// Dev build task - clean build with version set to 'dev'
tasks.register('buildDev') {
group = 'build'
Expand All @@ -205,6 +216,18 @@ tasks.named('build') {
mustRunAfter 'clean'
}

// Sentry source context upload (reads token from .sentry-auth-token file or SENTRY_AUTH_TOKEN env var)
sentry {
includeSourceContext = true
org = "hypersystems"
projectName = "hyperfactions"
authToken = {
def tokenFile = file('.sentry-auth-token')
if (tokenFile.exists()) return tokenFile.text.trim()
return System.getenv("SENTRY_AUTH_TOKEN")
}()
}

// Maven publication for JitPack (publishes API classes, not the shadow JAR)
publishing {
publications {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/hyperfactions/HyperFactions.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import com.hyperfactions.update.UpdateChecker;
import com.hyperfactions.update.UpdateNotificationListener;
import com.hyperfactions.update.UpdateNotificationPreferences;
import com.hyperfactions.util.ErrorHandler;
import com.hyperfactions.util.Logger;
import com.hyperfactions.worldmap.MapPlayerFilterService;
import com.hyperfactions.worldmap.WorldMapService;
Expand Down Expand Up @@ -245,7 +246,7 @@ public void enable() {
Files.writeString(versionFile, "1");
}
} catch (IOException e) {
Logger.severe("[Storage] Failed to initialize data directory: %s", e.getMessage());
ErrorHandler.report("[Storage] Failed to initialize data directory", e);
}

// Initialize HyperPerms integration (legacy, for backward compatibility)
Expand Down
15 changes: 8 additions & 7 deletions src/main/java/com/hyperfactions/backup/BackupManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.hyperfactions.HyperFactions;
import com.hyperfactions.config.ConfigManager;
import com.hyperfactions.storage.StorageUtils;
import com.hyperfactions.util.ErrorHandler;
import com.hyperfactions.util.Logger;
import java.io.FileOutputStream;
import java.io.IOException;
Expand Down Expand Up @@ -88,7 +89,7 @@ public void init() {
initialized = true;
Logger.info("[Backup] Initialized, backup directory: %s", backupsDir);
} catch (IOException e) {
Logger.severe("[Backup] Failed to create backups directory: %s", e.getMessage());
ErrorHandler.report("[Backup] Failed to create backups directory", e);
}
}

Expand Down Expand Up @@ -202,7 +203,7 @@ private void runScheduledBackup() {
}
}
}).exceptionally(ex -> {
Logger.severe("[Backup] Backup task failed with exception: %s", ex.getMessage());
ErrorHandler.report("[Backup] Backup task failed with exception", ex);
synchronized (backupLock) {
backupInProgress = false;
backupLock.notifyAll();
Expand All @@ -214,7 +215,7 @@ private void runScheduledBackup() {
backupInProgress = false;
backupLock.notifyAll();
}
Logger.severe("[Backup] Failed to start backup: %s", e.getMessage());
ErrorHandler.report("[Backup] Failed to start backup", e);
}
}

Expand Down Expand Up @@ -353,7 +354,7 @@ public CompletableFuture<BackupResult> createBackup(
try {
Files.deleteIfExists(backupFile);
} catch (IOException ignored) {}
Logger.severe("[Backup] Failed to create backup: %s", e.getMessage());
ErrorHandler.report("[Backup] Failed to create backup", e);
return new BackupResult.Failure("Failed to create backup: " + e.getMessage());
}
});
Expand Down Expand Up @@ -397,7 +398,7 @@ public CompletableFuture<RestoreResult> restoreBackup(@NotNull String backupName
return new RestoreResult.Success(backupName, filesRestored);

} catch (Exception e) {
Logger.severe("[Backup] Failed to restore backup: %s", e.getMessage());
ErrorHandler.report("[Backup] Failed to restore backup", e);
return new RestoreResult.Failure("Failed to restore backup: " + e.getMessage());
}
});
Expand All @@ -421,7 +422,7 @@ public CompletableFuture<Boolean> deleteBackup(@NotNull String backupName) {
Logger.info("[Backup] Deleted backup: %s", backupName);
return true;
} catch (Exception e) {
Logger.severe("[Backup] Failed to delete backup '%s': %s", backupName, e.getMessage());
ErrorHandler.report(String.format("[Backup] Failed to delete backup '%s'", backupName), e);
return false;
}
});
Expand Down Expand Up @@ -460,7 +461,7 @@ public List<BackupMetadata> listBackups() {
}
}
} catch (IOException e) {
Logger.severe("[Backup] Failed to list backups: %s", e.getMessage());
ErrorHandler.report("[Backup] Failed to list backups", e);
}

// Sort by timestamp, newest first
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/hyperfactions/chat/PublicChatListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.hyperfactions.HyperFactions;
import com.hyperfactions.config.ConfigManager;
import com.hyperfactions.util.ErrorHandler;
import com.hyperfactions.util.Logger;
import com.hypixel.hytale.event.EventPriority;
import com.hypixel.hytale.server.core.event.events.player.PlayerChatEvent;
Expand Down Expand Up @@ -65,7 +66,7 @@ public CompletableFuture<PlayerChatEvent> onPlayerChatAsync(
try {
return handleChatEvent(event);
} catch (Exception e) {
Logger.severe("Error handling chat event", e);
ErrorHandler.report("Error handling chat event", e);
return event;
}
});
Expand Down
69 changes: 69 additions & 0 deletions src/main/java/com/hyperfactions/command/admin/AdminSubCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import com.hyperfactions.Permissions;
import com.hyperfactions.command.admin.handler.AdminBackupHandler;
import com.hyperfactions.command.admin.handler.AdminDebugHandler;
import com.hyperfactions.config.ConfigManager;
import com.hyperfactions.integration.SentryIntegration;
import com.hyperfactions.command.admin.handler.AdminEconomyHandler;
import com.hyperfactions.command.admin.handler.AdminImportHandler;
import com.hyperfactions.command.admin.handler.AdminIntegrationHandler;
Expand Down Expand Up @@ -284,6 +286,8 @@ private void dispatchCommand(@NotNull CommandContext ctx, @Nullable Store<Entity
case "economy", "econ", "treasury" -> economyHandler.handleAdminEconomy(ctx, player, senderUuid, subArgs);
case "world", "worlds" -> worldHandler.handleAdminWorld(ctx, player, subArgs);
case "version" -> handleVersion(ctx, store, ref, player, isPlayer);
case "sentry" -> handleSentry(ctx, subArgs);
case "sentrytest" -> handleSentryTest(ctx);
case "log", "logs", "activitylog" -> {
if (!requirePlayer(ctx, isPlayer)) {
break;
Expand Down Expand Up @@ -375,6 +379,10 @@ private void showAdminHelp(CommandContext ctx) {
commands.add(new CommandHelp("/f admin log", "View global activity log"));
commands.add(new CommandHelp("/f admin world", "Per-world settings management"));
commands.add(new CommandHelp("/f admin version", "View mod version and integration status"));
commands.add(new CommandHelp("/f admin sentry", "View Sentry status"));
commands.add(new CommandHelp("/f admin sentry disable", "Opt out of Sentry error reporting"));
commands.add(new CommandHelp("/f admin sentry enable", "Opt in to Sentry error reporting"));
commands.add(new CommandHelp("/f admin sentrytest", "Send a test error to Sentry"));
ctx.sendMessage(HelpFormatter.buildHelp("Admin Commands", "Server administration", commands, null));
}

Expand Down Expand Up @@ -402,6 +410,67 @@ private void handleVersion(CommandContext ctx, @Nullable Store<EntityStore> stor
}
}

// === Sentry ===
private void handleSentry(CommandContext ctx, String[] args) {
var debugConfig = ConfigManager.get().debug();

if (args.length == 0) {
// Show status
boolean configEnabled = debugConfig.isSentryEnabled();
boolean running = SentryIntegration.isInitialized();
ctx.sendMessage(prefix().insert(msg("Sentry Error Reporting", COLOR_CYAN)));
ctx.sendMessage(msg(" Config: " + (configEnabled ? "enabled" : "disabled"),
configEnabled ? COLOR_GREEN : COLOR_GRAY));
ctx.sendMessage(msg(" Status: " + (running ? "active" : "inactive"),
running ? COLOR_GREEN : COLOR_GRAY));
ctx.sendMessage(msg(" DSN: " + debugConfig.getSentryDsn(), COLOR_GRAY));
ctx.sendMessage(msg(" Environment: " + debugConfig.getSentryEnvironment(), COLOR_GRAY));
return;
}

switch (args[0].toLowerCase()) {
case "disable", "optout", "off" -> {
if (!debugConfig.isSentryEnabled()) {
ctx.sendMessage(prefix().insert(msg("Sentry is already disabled.", COLOR_YELLOW)));
return;
}
debugConfig.setSentryEnabled(false);
debugConfig.save();
SentryIntegration.close();
ctx.sendMessage(prefix().insert(msg("Sentry disabled and config saved. Error reporting is now off.", COLOR_GREEN)));
}
case "enable", "optin", "on" -> {
if (debugConfig.isSentryEnabled()) {
ctx.sendMessage(prefix().insert(msg("Sentry is already enabled.", COLOR_YELLOW)));
return;
}
debugConfig.setSentryEnabled(true);
debugConfig.save();
// Try to initialize now if not already running
if (!SentryIntegration.isInitialized()) {
SentryIntegration.init(debugConfig);
}
ctx.sendMessage(prefix().insert(msg("Sentry enabled and config saved. Error reporting is now on.", COLOR_GREEN)));
}
default -> ctx.sendMessage(prefix().insert(msg("Usage: /f admin sentry [disable|enable]", COLOR_RED)));
}
}

// === Sentry Test ===
private void handleSentryTest(CommandContext ctx) {
if (!SentryIntegration.isInitialized()) {
ctx.sendMessage(prefix().insert(msg("Sentry is not initialized. Check config/debug.json", COLOR_RED)));
return;
}

boolean sent = SentryIntegration.sendTestEvent();
if (sent) {
ctx.sendMessage(prefix().insert(msg("Test error sent to Sentry. Check your Sentry dashboard.", COLOR_GREEN)));
} else {
ctx.sendMessage(prefix().insert(msg("Failed to send test event.", COLOR_RED)));
}
}

// === Reload ===
private void handleReload(CommandContext ctx, PlayerRef player) {
if (!hasPermission(player, Permissions.ADMIN)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.hyperfactions.manager.EconomyManager;
import com.hyperfactions.util.CommandHelp;
import com.hyperfactions.util.HelpFormatter;
import com.hyperfactions.util.ErrorHandler;
import com.hyperfactions.util.Logger;
import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.CommandContext;
Expand Down Expand Up @@ -156,7 +157,7 @@ private void handleSet(CommandContext ctx, EconomyManager econ, UUID senderUuid,
ctx.sendMessage(prefix().insert(msg("Failed: " + result.name(), COLOR_RED)));
}
}).exceptionally(ex -> {
Logger.severe("Admin economy set balance failed for %s", ex, faction.name());
ErrorHandler.report(String.format("Admin economy set balance failed for %s", faction.name()), ex);
ctx.sendMessage(prefix().insert(msg("An error occurred.", COLOR_RED)));
return null;
});
Expand Down Expand Up @@ -198,7 +199,7 @@ private void handleAdd(CommandContext ctx, EconomyManager econ, UUID senderUuid,
ctx.sendMessage(prefix().insert(msg("Failed: " + result.name(), COLOR_RED)));
}
}).exceptionally(ex -> {
Logger.severe("Admin economy add failed for %s", ex, faction.name());
ErrorHandler.report(String.format("Admin economy add failed for %s", faction.name()), ex);
ctx.sendMessage(prefix().insert(msg("An error occurred.", COLOR_RED)));
return null;
});
Expand Down Expand Up @@ -240,7 +241,7 @@ private void handleTake(CommandContext ctx, EconomyManager econ, UUID senderUuid
ctx.sendMessage(prefix().insert(msg("Failed: " + result.name(), COLOR_RED)));
}
}).exceptionally(ex -> {
Logger.severe("Admin economy take failed for %s", ex, faction.name());
ErrorHandler.report(String.format("Admin economy take failed for %s", faction.name()), ex);
ctx.sendMessage(prefix().insert(msg("An error occurred.", COLOR_RED)));
return null;
});
Expand Down Expand Up @@ -287,7 +288,7 @@ private void handleReset(CommandContext ctx, EconomyManager econ, UUID senderUui
ctx.sendMessage(prefix().insert(msg("Failed: " + result.name(), COLOR_RED)));
}
}).exceptionally(ex -> {
Logger.severe("Admin economy reset failed for %s", ex, faction.name());
ErrorHandler.report(String.format("Admin economy reset failed for %s", faction.name()), ex);
ctx.sendMessage(prefix().insert(msg("An error occurred.", COLOR_RED)));
return null;
});
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/com/hyperfactions/config/ConfigFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hyperfactions.util.ErrorHandler;
import com.hyperfactions.util.Logger;
import java.io.IOException;
import java.nio.file.Files;
Expand Down Expand Up @@ -93,7 +94,7 @@ public void load() {
save();
}
} catch (Exception e) {
Logger.severe("[Config] Failed to load %s: %s", filePath.getFileName(), e.getMessage());
ErrorHandler.report(String.format("[Config] Failed to load %s", filePath.getFileName()), e);
createDefaults();
}
}
Expand All @@ -109,7 +110,7 @@ public void save() {
needsSave = false;
Logger.debug("[Config] Saved: %s", filePath.getFileName());
} catch (IOException e) {
Logger.severe("[Config] Failed to save %s: %s", filePath.getFileName(), e.getMessage());
ErrorHandler.report(String.format("[Config] Failed to save %s", filePath.getFileName()), e);
}
}

Expand Down
Loading