diff --git a/hawk-java/src/main/java/org/catcher/CustomUncaughtExceptionHandler.java b/hawk-java/src/main/java/org/catcher/CustomUncaughtExceptionHandler.java deleted file mode 100644 index 84ea99e..0000000 --- a/hawk-java/src/main/java/org/catcher/CustomUncaughtExceptionHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.catcher; - -/** - * Custom handler for uncaught exceptions in threads. - */ -public class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { - private final Thread.UncaughtExceptionHandler defaultHandler; - - /** - * Initializes the custom handler and stores the default handler. - */ - public CustomUncaughtExceptionHandler() { - this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); - } - - /** - * Handles uncaught exceptions by logging them and invoking the default handler. - * - * @param t the thread that threw the exception - * @param e the thrown exception - */ - @Override - public void uncaughtException(Thread t, Throwable e) { - System.out.printf("Exception in thread %s: %s\n", t.getName(), e.getMessage()); - e.printStackTrace(); - - if (defaultHandler != null) { - defaultHandler.uncaughtException(t, e); - } - } - /** - * Enables this handler as the default uncaught exception handler. - */ - public void enable() { - Thread.setDefaultUncaughtExceptionHandler(this); - } -} \ No newline at end of file diff --git a/hawk-java/src/main/java/org/catcher/Hawk.java b/hawk-java/src/main/java/org/catcher/Hawk.java deleted file mode 100644 index 461d10d..0000000 --- a/hawk-java/src/main/java/org/catcher/Hawk.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.catcher; - -/** - * Manages uncaught exception handling in the application. - */ -public class Hawk { - private static volatile Hawk instance; - private final CustomUncaughtExceptionHandler exceptionHandler; - - /** - * Returns the singleton instance of HawkCatcher. - * - * @return the singleton instance - */ - private static Hawk getInstance() { - if (instance == null) { - synchronized (Hawk.class) { - if (instance == null) { - instance = new Hawk(); - } - } - } - return instance; - } - - /** - * Initializes a new HawkCatcher instance. - */ - private Hawk(){ - this.exceptionHandler = new CustomUncaughtExceptionHandler(); - } - - /** - * Sets the custom handler as the default uncaught exception handler. - */ - public static void init(){ - getInstance().exceptionHandler.enable(); - } -} diff --git a/hawk-java/src/main/java/org/playground/PlaygroundApp.java b/hawk-java/src/main/java/org/playground/PlaygroundApp.java deleted file mode 100644 index f4ce405..0000000 --- a/hawk-java/src/main/java/org/playground/PlaygroundApp.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.playground; - -import org.catcher.Hawk; - -/** - * PlaygroundApp demonstrates the use of HawkCatcher for handling uncaught exceptions. - */ -public class PlaygroundApp { - - /** - * The main method initializes the HawkCatcher and runs test scenarios. - * - * @param args command line arguments - */ - public static void main(String[] args) { - Hawk.init(); - - runTestScenarios(); - } - - /** - * Runs various test scenarios that throw different types of exceptions. - */ - private static void runTestScenarios() { - Thread scenario1 = new Thread(() -> { - throw new RuntimeException("Test Exception from Scenario 1"); - }); - scenario1.start(); - - Thread scenario2 = new Thread(() -> { - int[] arr = new int[5]; - System.out.println(arr[10]); // This will throw ArrayIndexOutOfBoundsException - }); - scenario2.start(); - - Thread scenario3 = new Thread(() -> { - String str = null; - System.out.println(str.length()); // This will throw NullPointerException - }); - scenario3.start(); - - Thread scenario4 = new Thread(() -> { - throw new IllegalArgumentException("Illegal Argument Exception from Scenario 4"); - }); - scenario4.start(); - - Thread scenario5 = new Thread(() -> { - try { - throw new Exception("Checked Exception from Scenario 5"); - } catch (Exception e) { - throw new RuntimeException(e); - } - }); - scenario5.start(); - } -} \ No newline at end of file diff --git a/hawk-spring/src/main/java/so/java/hawk/catcher/HawkCatcher.java b/hawk-spring/src/main/java/so/java/hawk/catcher/HawkCatcher.java new file mode 100644 index 0000000..615b3f9 --- /dev/null +++ b/hawk-spring/src/main/java/so/java/hawk/catcher/HawkCatcher.java @@ -0,0 +1,59 @@ +package so.java.hawk.catcher; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +/** + * HawkCatcher Class + * + * Provides methods for global error handling, logging errors and warnings, and reporting status. + */ +@Component +public class HawkCatcher { + + private static final Logger logger = LoggerFactory.getLogger(HawkCatcher.class); + private static int errorCount = 0; + private static int warningCount = 0; + + /** + * Initializes the global error handler and logging mechanisms. + * Sets up uncaught exception handler for the entire JVM. + */ + @PostConstruct + public void initialize() { + Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> { + logError("Uncaught exception in thread " + thread.getName() + ": " + exception.getMessage()); + }); + } + + /** + * Logs error messages to the console and increments the error counter. + * + * @param message The error message to log. + */ + public static void logError(String message) { + errorCount++; + logger.error("Error: " + message); + } + + /** + * Logs warning messages to the console and increments the warning counter. + * + * @param message The warning message to log. + */ + public static void logWarning(String message) { + warningCount++; + logger.warn("Warning: " + message); + } + + /** + * Reports the current status of errors and warnings. + */ + public static void reportStatus() { + String statusMessage = String.format("Current Status:%nErrors: %d%nWarnings: %d", errorCount, warningCount); + logger.info(statusMessage); + } +} \ No newline at end of file diff --git a/hawk-spring/src/main/java/so/java/hawk/catcher/PlaygroundApp.java b/hawk-spring/src/main/java/so/java/hawk/catcher/PlaygroundApp.java new file mode 100644 index 0000000..c300110 --- /dev/null +++ b/hawk-spring/src/main/java/so/java/hawk/catcher/PlaygroundApp.java @@ -0,0 +1,71 @@ +package so.java.hawk.catcher; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +/** + * PlaygroundApp Class + *
+ * The main application class for running HawkCatcher example.
+ * Initializes the HawkCatcher and demonstrates logging errors, warnings, and reporting status.
+ */
+@SpringBootApplication
+@ComponentScan(basePackages = {"so.java.hawk.catcher", "so.java.hawk"}) // Add the packages to scan
+public class PlaygroundApp {
+
+ private final HawkCatcher hawkCatcher;
+
+ /**
+ * Constructor for PlaygroundApp.
+ *
+ * @param hawkCatcher HawkCatcher instance
+ */
+ public PlaygroundApp(HawkCatcher hawkCatcher) {
+ this.hawkCatcher = hawkCatcher;
+ }
+
+ /**
+ * Main method to run the application.
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String[] args) {
+ SpringApplication.run(PlaygroundApp.class, args);
+ }
+
+ /**
+ * CommandLineRunner bean to execute actions after application startup.
+ * Demonstrates logging warnings, handling exceptions, and reporting status.
+ *
+ * @return CommandLineRunner instance
+ */
+ @Bean
+ CommandLineRunner run() {
+ return args -> {
+ // Log a warning manually
+ hawkCatcher.logWarning("This is a test warning.");
+
+ // Run a critical operation and handle any exceptions
+ try {
+ performCriticalOperation();
+ } catch (Exception e) {
+ hawkCatcher.logError("Caught an exception in critical operation: " + e.getMessage());
+ }
+
+ // Report current error status to check if there were issues
+ hawkCatcher.reportStatus();
+ };
+ }
+
+ /**
+ * Perform a critical operation (example: division by zero).
+ * This will cause an exception to demonstrate error handling.
+ */
+ private void performCriticalOperation() {
+ // Example error: division by zero
+ int result = 10 / 0;
+ }
+}
\ No newline at end of file
diff --git a/hawk-spring/src/main/java/so/java/hawk/handler/GlobalExceptionHandler.java b/hawk-spring/src/main/java/so/java/hawk/handler/GlobalExceptionHandler.java
new file mode 100644
index 0000000..21fe8e7
--- /dev/null
+++ b/hawk-spring/src/main/java/so/java/hawk/handler/GlobalExceptionHandler.java
@@ -0,0 +1,41 @@
+package so.java.hawk.handler;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import so.java.hawk.catcher.HawkCatcher;
+
+/**
+ * GlobalExceptionHandler Class
+ *
+ * Handles global exceptions for the application. It catches any unhandled exceptions,
+ * logs them using HawkCatcher, and returns a generic error response.
+ */
+@ControllerAdvice
+public class GlobalExceptionHandler {
+
+ private final HawkCatcher hawkCatcher;
+
+ /**
+ * Constructor for GlobalExceptionHandler.
+ *
+ * @param hawkCatcher HawkCatcher instance
+ */
+ public GlobalExceptionHandler(HawkCatcher hawkCatcher) {
+ this.hawkCatcher = hawkCatcher;
+ }
+
+ /**
+ * Global exception handler for any Exception thrown within the application.
+ * Logs the exception and sends an HTTP 500 response with the error message.
+ *
+ * @param exception The exception that was thrown
+ * @return A ResponseEntity containing the error message and HTTP status
+ */
+ @ExceptionHandler(Exception.class)
+ public ResponseEntity