Replace System.exit with exceptions for safer shutdown

Refactored various parts of the application to replace calls to `System.exit` with appropriate `IllegalStateException` usage. Improved modularity and testability by delegating error handling to specific exception cases instead of terminating the JVM directly. Updated related components to ensure proper cleanup and graceful shutdown behavior during failures.
This commit is contained in:
anthorob committed 2026-09-25 06:46:31 -04:00
1 parent 4277db3922
commit ffb1095f23
4 files changed
+9 -5

No files matched your search

@@ -94,7 +94,9 @@ public class App {
context.start(); context.start();
} catch (Exception e) { } catch (Exception e) {
LogHandler.log(e); LogHandler.log(e);
System.exit(1); // Roll back the components that did start so no non-daemon thread keeps the JVM alive.
context.stop();
throw new IllegalStateException("Startup failed", e);
} }
Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown)); Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));
@@ -206,8 +208,11 @@ public class App {
.build(); .build();
jda.awaitReady(); jda.awaitReady();
} catch (InvalidTokenException | IllegalArgumentException | InterruptedException e) { } catch (InvalidTokenException | IllegalArgumentException | InterruptedException e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LogHandler.log(e); LogHandler.log(e);
System.exit(1); throw new IllegalStateException("Unable to connect to Discord", e);
} }
} }
@@ -32,7 +32,7 @@ public class DatabaseMigration {
logger.info("Database migrations finished successfully! (total: {})", result.migrationsExecuted); logger.info("Database migrations finished successfully! (total: {})", result.migrationsExecuted);
} catch (Exception e) { } catch (Exception e) {
logger.error(e); logger.error(e);
System.exit(1); throw new IllegalStateException("Database migration failed", e);
} }
} }
} }
@@ -89,7 +89,7 @@ public class SessionManager implements SessionProvider {
stop(); stop();
logger.error("Error connecting to database. Shutting down.."); logger.error("Error connecting to database. Shutting down..");
System.exit(1); throw new IllegalStateException("Unable to connect to the database", e);
} }
} }
@@ -76,7 +76,6 @@ public final class ActionRoutes {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
shutdownHook.run(); shutdownHook.run();
System.exit(0);
}); });
} }
} }