From 418cc8cbc177afdeb7ba86e8498fe3ee7fd07844 Mon Sep 17 00:00:00 2001 From: Rainnny7 Date: Sat, 6 Apr 2024 00:07:38 -0400 Subject: [PATCH] Error handling --- .../exception/ExceptionControllerAdvice.java | 30 +++++++++++++++++++ .../impl/ResourceNotFoundException.java | 15 ++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/main/java/me/braydon/mc/exception/ExceptionControllerAdvice.java create mode 100644 src/main/java/me/braydon/mc/exception/impl/ResourceNotFoundException.java diff --git a/src/main/java/me/braydon/mc/exception/ExceptionControllerAdvice.java b/src/main/java/me/braydon/mc/exception/ExceptionControllerAdvice.java new file mode 100644 index 0000000..d38b0c3 --- /dev/null +++ b/src/main/java/me/braydon/mc/exception/ExceptionControllerAdvice.java @@ -0,0 +1,30 @@ +package me.braydon.mc.exception; + +import lombok.NonNull; +import me.braydon.mc.model.response.ErrorResponse; +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 org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Advice for handling raised exceptions. + * + * @author Braydon + */ +@ControllerAdvice +public final class ExceptionControllerAdvice { + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(@NonNull Exception ex) { + HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; // Get the HTTP status + if (ex.getClass().isAnnotationPresent(ResponseStatus.class)) { // Get from the @ResponseStatus annotation + status = ex.getClass().getAnnotation(ResponseStatus.class).value(); + } + String message = ex.getLocalizedMessage(); // Get the error message + if (message == null) { // Fallback + message = "An internal error has occurred."; + } + return new ResponseEntity<>(new ErrorResponse(status, message), status); + } +} \ No newline at end of file diff --git a/src/main/java/me/braydon/mc/exception/impl/ResourceNotFoundException.java b/src/main/java/me/braydon/mc/exception/impl/ResourceNotFoundException.java new file mode 100644 index 0000000..31c37ba --- /dev/null +++ b/src/main/java/me/braydon/mc/exception/impl/ResourceNotFoundException.java @@ -0,0 +1,15 @@ +package me.braydon.mc.exception.impl; + +import lombok.experimental.StandardException; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * This exception is raised + * when a resource is not found. + * + * @author Braydon + */ +@StandardException +@ResponseStatus(HttpStatus.NOT_FOUND) +public final class ResourceNotFoundException extends RuntimeException { } \ No newline at end of file