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
Author
Since Spring Boot 2.6.x we need to include server errors explicitly, stacktrace etc.
So, configure your application.properties like this:
server.error.include-message=always
server.error.include-binding-errors=always
server.error.include-stacktrace=on_param
server.error.include-exception=falseOr configure your application.yml like this:
server:
error:
include-message: always
include-binding-errors: always
include-stacktrace: on_param
include-exception: false
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Spring Boot
MockMvcdoes NOT send payload when there's a expcetion of typesResponseStatusExceptionorMethodArgumentNotValidExceptionduring the tests. It happens becauseMockMvcis NOT a real Servlet environment.Some issues:
Here one of many workarounds to handle this issue:
And a Java version: