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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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