Created
October 7, 2021 12:35
-
-
Save rponte/3715070f5ed2c0888af953706c29ef5e to your computer and use it in GitHub Desktop.
Spring Boot: custom and simple exception handler (using the default payload generated by Spring)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.slf4j.Logger; | |
| import org.slf4j.LoggerFactory; | |
| import org.springframework.dao.DataAccessException; | |
| import org.springframework.http.ResponseEntity; | |
| import org.springframework.web.bind.annotation.ExceptionHandler; | |
| import org.springframework.web.bind.annotation.RestControllerAdvice; | |
| import org.springframework.web.context.request.WebRequest; | |
| import java.time.LocalDateTime; | |
| import java.util.Map; | |
| @RestControllerAdvice | |
| public class CustomExceptionHandler { | |
| private static final Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class); | |
| @ExceptionHandler(DataAccessException.class) | |
| public ResponseEntity<?> handleDatabaseErrors(Exception ex, WebRequest request) { | |
| logger.error("Catching an unhandled database exception thrown by a controller: " + ex.getLocalizedMessage(), ex); | |
| Map<String, Object> body = Map.of( | |
| "status", 500, | |
| "error", "Internal Server Error", | |
| "path", request.getDescription(false).replace("uri=", ""), | |
| "timestamp", LocalDateTime.now(), | |
| "message", "Ocorreu um erro interno. Por favor contate o administrador." | |
| ); | |
| return ResponseEntity | |
| .internalServerError().body(body); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since Spring Boot 2.6.x we need to include server errors explicitly, stacktrace etc.
So, configure your
application.propertieslike this:Or configure your
application.ymllike this: