From 44a135602fc4bf756c275816ab11fcea1ee5fcd1 Mon Sep 17 00:00:00 2001 From: yash raj Date: Sat, 27 Jul 2024 18:41:00 +0530 Subject: [PATCH] improve the internal server error exception handler by adding time stamp, error message and details --- .../exceptions/GlobalExceptionHandler.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/skill-tree/src/main/java/com/RDS/skilltree/exceptions/GlobalExceptionHandler.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/GlobalExceptionHandler.java index f42d241..60d4bff 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/exceptions/GlobalExceptionHandler.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/GlobalExceptionHandler.java @@ -2,7 +2,6 @@ import com.RDS.skilltree.utils.GenericResponse; import jakarta.validation.ConstraintViolationException; -import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.tomcat.websocket.AuthenticationException; import org.springframework.http.HttpStatus; @@ -15,6 +14,11 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Slf4j @ControllerAdvice public class GlobalExceptionHandler { @@ -139,8 +143,16 @@ public ResponseEntity handleForbiddenException(ForbiddenException ex, WebRequ @ExceptionHandler(InternalServerErrorException.class) public ResponseEntity handleInternalServerErrorException( InternalServerErrorException ex, WebRequest request) { - log.error("Exception - Error : {}", ex.getMessage(), ex); - return new ResponseEntity<>( - new GenericResponse<>(null, ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); + log.error("Internal Server Error", ex); + // Create a more specific error message based on the exception type or cause + String errorMessage = "An unexpected error occurred."; + + // Consider adding more details to the response for debugging + Map errorDetails = new HashMap<>(); + errorDetails.put("timestamp", LocalDateTime.now()); + errorDetails.put("message", errorMessage); + errorDetails.put("details", ex.getMessage()); // Include exception details for debugging + + return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); } }